public void LoadMappings(IList <MappingConfiguration> configurationMappings)
        {
            if (configurationMappings == null)
            {
                throw new ArgumentNullException("configurationMappings");
            }

            foreach (MappingConfiguration mc in configurationMappings)
            {
                if (!string.IsNullOrEmpty(mc.Assembly) && string.IsNullOrEmpty(mc.Resource))
                {
                    log.DebugFormat("Assembly {0}", mc.Assembly);
                    AddAssembly(mc.Assembly);
                }
                else if (!string.IsNullOrEmpty(mc.Assembly) && !string.IsNullOrEmpty(mc.Resource))
                {
                    log.DebugFormat("Resource {0} in {1}", mc.Resource, mc.Assembly);
                    AddResource(Assembly.Load(mc.Assembly), mc.Resource);
                }
                else if (!string.IsNullOrEmpty(mc.File))
                {
                    log.DebugFormat("File {0}", mc.File);
                    AddFile(mc.File);
                }
                else
                {
                    log.WarnFormat(
                        "Mapping configuration ignored: Assembly>{0}< Resource>{1}< File>{2}<",
                        mc.Assembly, mc.Resource, mc.File);
                }
            }
        }
        public virtual void Put(object key, object value)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key", "null key not allowed");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value", "null value not allowed");
            }

            if (Log.IsDebugEnabled)
            {
                Log.DebugFormat("setting value for item {0}", key);
            }

            var client = _clientManager.GetDatabase();

            var cacheKey = KeyAsString(key);
            var returnOk = client.StringSet(cacheKey,
                                            _serializer.Serialize(new DictionaryEntry(GetAlternateKeyHash(key), value)),
                                            _expiryTimeSpan);

            if (!returnOk)
            {
                if (Log.IsWarnEnabled)
                {
                    Log.WarnFormat("could not save: {0} => {1}", key, value);
                }
            }
        }
예제 #3
0
        public void ValidateLogoutRequest(string requestType, System.Collections.Specialized.NameValueCollection requestParams, Uri requestUrl)
        {
            logger.DebugFormat(TraceMessages.LogoutResponseReceived);

            var            message  = string.Empty;
            LogoutResponse response = null;

            switch (requestType)
            {
            case "GET":
                ValidateLogoutViaGet(requestUrl, out message, out response);
                break;

            case "POST":
                ValidateLogoutViaPost(requestParams, out message, out response);
                break;

            default:
                break;
            }

            if (response == null)
            {
                logger.ErrorFormat(ErrorMessages.UnsupportedRequestType, requestType);
                throw new Saml20Exception(string.Format(ErrorMessages.UnsupportedRequestType, requestType));
            }

            logger.DebugFormat(TraceMessages.LogoutResponseParsed, message);

            if (response.Status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                logger.ErrorFormat(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value);
                throw new Saml20Exception(string.Format(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value));
            }
        }
예제 #4
0
        /// <summary>
        /// Get the object from the Cache
        /// </summary>
        /// <param name="key">the id of the item to get from the cache</param>
        /// <returns>the item stored in the cache with the id specified by <paramref name="key"/></returns>
        public object Get(object key)
        {
            if (key == null)
            {
                return(null);
            }

            //get the full key to use to locate the item in the cache
            string cacheKey = GetCacheKey(key);

            if (Log.IsDebugEnabled)
            {
                Log.DebugFormat("Fetching object '{0}' from the cache.", cacheKey);
            }

            object cachedObject = _webCache.Get(cacheKey, RegionName);

            if (cachedObject == null || !(cachedObject is byte[]))
            {
                if (_name == "UpdateTimestampsCache")
                {
                    Put(key, long.MinValue);
                    return(long.MinValue);
                }
                return(null);
            }

            return(_serializationProvider.Deserialize(cachedObject as byte[]));
        }
예제 #5
0
        public RedisCache(string regionName, IDictionary <string, string> properties, RedisCacheElement element, ConnectionMultiplexer connectionMultiplexer, RedisCacheProviderOptions options)
        {
            this.connectionMultiplexer = connectionMultiplexer.ThrowIfNull("connectionMultiplexer");
            this.options = options.ThrowIfNull("options").ShallowCloneAndValidate();

            RegionName = regionName.ThrowIfNull("regionName");

            if (element == null)
            {
                expiry = TimeSpan.FromSeconds(
                    PropertiesHelper.GetInt32(Cfg.Environment.CacheDefaultExpiration, properties, DefaultExpiry)
                    );
            }
            else
            {
                expiry = element.Expiration;
            }

            log.DebugFormat("using expiration : {0} seconds", expiry.TotalSeconds);

            var @namespace = CacheNamePrefix + RegionName;

            CacheNamespace = new RedisNamespace(@namespace);
            SyncInitialGeneration();
        }
예제 #6
0
        public IList List()
        {
            using (new SessionIdLoggingContext(session.SessionId))
            {
                bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable;

                CreateCriteriaLoaders();
                CombineCriteriaQueries();

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Multi criteria with {0} criteria queries.", criteriaQueries.Count);
                    for (int i = 0; i < criteriaQueries.Count; i++)
                    {
                        log.DebugFormat("Query #{0}: {1}", i, criteriaQueries[i]);
                    }
                }

                if (cacheable)
                {
                    criteriaResults = ListUsingQueryCache();
                }
                else
                {
                    criteriaResults = ListIgnoreQueryCache();
                }

                return(criteriaResults);
            }
        }
예제 #7
0
        /// <summary>
        /// Return the query results of all the queries
        /// </summary>
        public IList List()
        {
            using (new SessionIdLoggingContext(session.SessionId))
            {
                bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable;
                combinedParameters = CreateCombinedQueryParameters();

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Multi query with {0} queries.", queries.Count);
                    for (int i = 0; i < queries.Count; i++)
                    {
                        log.DebugFormat("Query #{0}: {1}", i, queries[i]);
                    }
                }

                try
                {
                    Before();
                    return(cacheable ? ListUsingQueryCache() : ListIgnoreQueryCache());
                }
                finally
                {
                    After();
                }
            }
        }
예제 #8
0
        public int ExecuteNonQuery(IDbCommand cmd)
        {
            CheckReaders();
            LogCommand(cmd);
            Prepare(cmd);
            Stopwatch duration = null;

            if (log.IsDebugEnabled)
            {
                duration = Stopwatch.StartNew();
            }
            try
            {
                return(cmd.ExecuteNonQuery());
            }
            catch (Exception e)
            {
                e.Data["actual-sql-query"] = cmd.CommandText;
                log.Error("Could not execute command: " + cmd.CommandText, e);
                throw;
            }
            finally
            {
                if (log.IsDebugEnabled && duration != null)
                {
                    log.DebugFormat("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds);
                }
            }
        }
예제 #9
0
        public int ExecuteNonQuery(DbCommand cmd)
        {
            CheckReaders();
            LogCommand(cmd);
            Prepare(cmd);
            Stopwatch duration = null;

            if (Log.IsDebugEnabled)
            {
                duration = Stopwatch.StartNew();
            }
            try
            {
                return(cmd.ExecuteNonQuery());
            }
            catch (Exception e)
            {
                //Modified by OneGeo: Concatnating formatted SQLStatements with thrown errors.
                e.Data["actual-sql-query"] = _factory.Settings.SqlStatementLogger.SQLStatement;
                Log.Error("Could not execute command: " + _factory.Settings.SqlStatementLogger.SQLStatement, e);
                throw;
            }
            finally
            {
                if (Log.IsDebugEnabled && duration != null)
                {
                    Log.DebugFormat("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds);
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Handles the selection of an IDP. If only one IDP is found, the user is automatically redirected to it.
        /// If several are found, and nothing indicates to which one the user should be sent, this method returns null.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="config">Configuration.  If null, configuration will be populated from application config</param>
        /// <returns>The <see cref="IdentityProvider"/>.</returns>
        public IdentityProvider RetrieveIDP(NameValueCollection allparams, NameValueCollection queryString, Saml2Configuration config, Action <string> redirectToSelection)
        {
            // If idpChoice is set, use it value
            if (!string.IsNullOrEmpty(allparams[IdpChoiceParameterName]))
            {
                logger.DebugFormat(TraceMessages.IdentityProviderRetreivedFromQueryString, allparams[IdpChoiceParameterName]);
                var endPoint = config.IdentityProvidersSource.GetById(allparams[IdpChoiceParameterName]);
                if (endPoint != null)
                {
                    return(endPoint);
                }
            }

            // If we have a common domain cookie, use it's value
            // It must have been returned from the local common domain cookie reader endpoint.
            if (!string.IsNullOrEmpty(queryString["_saml_idp"]))
            {
                var cdc = new Protocol.CommonDomainCookie(queryString["_saml_idp"]);
                if (cdc.IsSet)
                {
                    var endPoint = config.IdentityProvidersSource.GetById(cdc.PreferredIDP);
                    if (endPoint != null)
                    {
                        logger.DebugFormat(TraceMessages.IdentityProviderRetreivedFromCommonDomainCookie, cdc.PreferredIDP);
                        return(endPoint);
                    }

                    logger.WarnFormat(ErrorMessages.CommonDomainCookieIdentityProviderInvalid, cdc.PreferredIDP);
                }
            }

            // If there is only one configured IdentityProviderEndpointElement lets just use that
            if (config.IdentityProvidersSource.GetAll().Any())
            {
                var idp = config.IdentityProvidersSource.GetAll().First();
                logger.DebugFormat(TraceMessages.IdentityProviderRetreivedFromDefault, idp.Name);
                return(idp);
            }

            // If one of the endpoints are marked with default, use that one
            var defaultIDP = config.IdentityProvidersSource.GetAll().FirstOrDefault(idp => idp.Default);

            if (defaultIDP != null)
            {
                logger.DebugFormat(TraceMessages.IdentityProviderRetreivedFromDefault, defaultIDP.Id);
                return(defaultIDP);
            }

            // In case an IDP selection url has been configured, redirect to that one.
            if (!string.IsNullOrEmpty(config.IdentityProvidersSource.SelectionUrl))
            {
                logger.DebugFormat(TraceMessages.IdentityProviderRetreivedFromSelection, config.IdentityProvidersSource.SelectionUrl);
                redirectToSelection(config.IdentityProvidersSource.SelectionUrl);
                return(null);
            }

            // If an IDPSelectionEvent handler is present, request the handler for an IDP endpoint to use.
            return(IdpSelectionUtil.InvokeIDPSelectionEventHandler(config.IdentityProvidersSource));
        }
예제 #11
0
 public void Add(string entityName, long revision, object id, object entity)
 {
     if (log.IsDebugEnabled)
     {
         log.DebugFormat(logAdd, id, revision, entityName);
     }
     cache.Add(new Tuple <string, long, object>(entityName, revision, id), entity);
 }
 private static void addMemberMetaAndLog(System.Type type, MemberInfoAndAttribute memberInfoAndAttribute, EntityMeta entMeta)
 {
     log.DebugFormat("Adding {0} to member {1} on type {2}.",
                     memberInfoAndAttribute.Attribute.GetType().Name,
                     memberInfoAndAttribute.MemberInfo.Name,
                     type.FullName);
     entMeta.AddMemberMeta(memberInfoAndAttribute.MemberInfo, memberInfoAndAttribute.Attribute);
 }
        public ICriteria GetCriteria(string path)
        {
            ICriteria result;

            associationPathCriteriaMap.TryGetValue(path, out result);
            logger.DebugFormat("getCriteria for path={0} crit={1}", path, result);
            return(result);
        }
        /// <summary> Try to initialize a collection from the cache</summary>
        private bool InitializeCollectionFromCache(object id, ICollectionPersister persister, IPersistentCollection collection, ISessionImplementor source)
        {
            if (!(source.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(source))
            {
                log.Debug("disregarding cached version (if any) of collection due to enabled filters ");
                return(false);
            }

            bool useCache = persister.HasCache && source.CacheMode.HasFlag(CacheMode.Get);

            if (!useCache)
            {
                return(false);
            }
            else
            {
                ISessionFactoryImplementor factory = source.Factory;

                CacheKey ck = source.GenerateCacheKey(id, persister.KeyType, persister.Role);
                object   ce = persister.Cache.Get(ck, source.Timestamp);

                if (factory.Statistics.IsStatisticsEnabled)
                {
                    if (ce == null)
                    {
                        factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName);
                    }
                    else
                    {
                        factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName);
                    }
                }

                if (ce == null)
                {
                    log.DebugFormat("Collection cache miss: {0}", ck);
                }
                else
                {
                    log.DebugFormat("Collection cache hit: {0}", ck);
                }

                if (ce == null)
                {
                    return(false);
                }
                else
                {
                    IPersistenceContext persistenceContext = source.PersistenceContext;

                    CollectionCacheEntry cacheEntry = (CollectionCacheEntry)persister.CacheEntryStructure.Destructure(ce, factory);
                    cacheEntry.Assemble(collection, persister, persistenceContext.GetCollectionOwner(id, persister));

                    persistenceContext.GetCollectionEntry(collection).PostInitialize(collection);
                    return(true);
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Handles the SOAP message.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="inputStream">The input stream.</param>
        private async Task HandleSoap(IOwinContext context, Stream inputStream, NameValueCollection requestParams)
        {
            var config = options.Configuration;

            var parser = new HttpArtifactBindingParser(inputStream);

            Logger.DebugFormat(TraceMessages.SOAPMessageParse, parser.SamlMessage.OuterXml);

            var builder = GetBuilder(context);
            var idp     = IdpSelectionUtil.RetrieveIDPConfiguration(parser.Issuer, config);

            if (parser.IsLogoutReqest)
            {
                Logger.DebugFormat(TraceMessages.LogoutRequestReceived, parser.SamlMessage.OuterXml);

                if (!parser.CheckSamlMessageSignature(idp.Metadata.Keys))
                {
                    Logger.ErrorFormat(ErrorMessages.ArtifactResolveSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.ArtifactResolveSignatureInvalid);
                }

                var req = parser.LogoutRequest;

                var logoutRequestReceivedNotification = new LogoutRequestReceivedNotification <LogoutRequest, SamlAuthenticationOptions>(context, options)
                {
                    ProtocolMessage = req
                };

                await options.Notifications.LogoutRequestReceived(logoutRequestReceivedNotification);

                DoLogout(context, true);

                // Build the response object
                var response = new Saml20LogoutResponse
                {
                    Issuer       = config.ServiceProvider.Id,
                    StatusCode   = Saml20Constants.StatusCodes.Success,
                    InResponseTo = req.Id
                };

                // response.Destination = destination.Url;
                var doc = response.GetXml();
                XmlSignatureUtils.SignDocument(doc, response.Id, config.ServiceProvider.SigningCertificate);
                if (doc.FirstChild is XmlDeclaration)
                {
                    doc.RemoveChild(doc.FirstChild);
                }

                SendResponseMessage(doc.OuterXml, context);
            }
            else
            {
                Logger.ErrorFormat(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
                throw new Saml20Exception(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
            }
        }
예제 #16
0
        private void Configure(CacheRegionElement settings, IDictionary <string, string> additionalProperties)
        {
            log.Debug("Configuring cache region");

            //these are some default conenction values that can be later used by the data dependencies
            //if no custome settings are specified
            string connectionName   = null;
            string connectionString = null;

            if (additionalProperties != null)
            {
                //pick up connection settings that might be used later for data dependencis if any are specified
                if (additionalProperties.ContainsKey(Environment.ConnectionStringName))
                {
                    connectionName = additionalProperties[Environment.ConnectionStringName];
                }

                if (additionalProperties.ContainsKey(Environment.ConnectionString))
                {
                    connectionString = additionalProperties[Environment.ConnectionString];
                }
            }

            if (settings != null)
            {
                //_priority = settings.Priority;
                _timeOfDayExpiration = settings.TimeOfDayExpiration;
                _relativeExpiration  = settings.RelativeExpiration;

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("using priority: {0}", settings.Priority.ToString("g"));

                    if (_relativeExpiration.HasValue)
                    {
                        log.DebugFormat("using relative expiration :{0}", _relativeExpiration);
                    }

                    if (_timeOfDayExpiration.HasValue)
                    {
                        log.DebugFormat("using time of day expiration : {0}", _timeOfDayExpiration);
                    }
                }

                CreateDependencyEnlisters(settings.Dependencies, connectionName, connectionString);
            }
            else
            {
                _priority = CacheItemPriority.Default;
            }

            if (_relativeExpiration.HasValue == false && _timeOfDayExpiration.HasValue == false)
            {
                _relativeExpiration = defaultRelativeExpiration;
            }
        }
예제 #17
0
        public static FilterDefinition CreateFilterDefinition(HbmFilterDef filterDefSchema)
        {
            log.DebugFormat("Parsing filter-def [{0}]", filterDefSchema.name);

            string defaultCondition = filterDefSchema.GetDefaultCondition();
            IDictionary <string, IType> parameterTypes = GetFilterParameterTypes(filterDefSchema);

            log.DebugFormat("Parsed filter-def [{0}]", filterDefSchema.name);

            return(new FilterDefinition(filterDefSchema.name, defaultCondition, parameterTypes, filterDefSchema.usemanytoone));
        }
예제 #18
0
        /// <summary>
        /// Performs the attribute query against the specified IdP endpoint and adds the resulting attributes to <c>Saml20Identity.Current</c>.
        /// </summary>
        /// <param name="context">The http context.</param>
        /// <param name="endPoint">The IdP to perform the query against.</param>
        /// <param name="nameIdFormat">The name id format.</param>
        public void PerformQuery(HttpContext context, IdentityProviderElement endPoint, string nameIdFormat)
        {
            Logger.DebugFormat("{0}.{1} called", GetType(), "PerformQuery()");

            var builder = new HttpSoapBindingBuilder(context);

            var name = new NameId
            {
                Value  = Saml20Identity.Current.Name,
                Format = nameIdFormat
            };

            _attrQuery.Subject.Items = new object[] { name };
            _attrQuery.SamlAttribute = _attributes.ToArray();

            var query = new XmlDocument();

            query.LoadXml(Serialization.SerializeToXmlString(_attrQuery));

            XmlSignatureUtils.SignDocument(query, Id);
            if (query.FirstChild is XmlDeclaration)
            {
                query.RemoveChild(query.FirstChild);
            }

            Logger.DebugFormat(TraceMessages.AttrQuerySent, endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml);

            Stream s;

            try
            {
                s = builder.GetResponse(endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml, endPoint.AttributeQuery);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }

            var parser = new HttpSoapBindingParser(s);
            var status = parser.GetStatus();

            if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                Logger.ErrorFormat(ErrorMessages.AttrQueryStatusNotSuccessful, Serialization.SerializeToXmlString(status));
                throw new Saml20Exception(status.StatusMessage);
            }

            bool isEncrypted;
            var  xmlAssertion = Saml20SignonHandler.GetAssertion(parser.SamlMessage, out isEncrypted);

            if (isEncrypted)
            {
                var ass = new Saml20EncryptedAssertion((RSA)Saml2Config.GetConfig().ServiceProvider.SigningCertificat
예제 #19
0
        public ICache BuildCache(string regionName, IDictionary <string, string> properties)
        {
            if (connectionMultiplexerStatic == null)
            {
                throw new InvalidOperationException(
                          "A 'ConnectionMultiplexer' must be configured with SetConnectionMultiplexer(). " +
                          "For example, call 'RedisCacheProvider.SetConnectionMultiplexer(ConnectionMultiplexer.Connect(\"localhost:6379\"))' " +
                          "before creating the ISessionFactory."
                          );
            }

            // Double-check so that we don't have to lock if necessary.
            if (optionsStatic == null)
            {
                lock (syncRoot)
                {
                    if (optionsStatic == null)
                    {
                        optionsStatic = new RedisCacheProviderOptions();
                    }
                }
            }

            if (log.IsDebugEnabled)
            {
                var sb = new StringBuilder();
                foreach (var pair in properties)
                {
                    sb.Append("name=");
                    sb.Append(pair.Key);
                    sb.Append("&value=");
                    sb.Append(pair.Value);
                    sb.Append(";");
                }
                log.DebugFormat("building cache with region: {0}, properties: {1}", regionName, sb);
            }

            RedisCacheConfiguration configuration = null;

            if (!String.IsNullOrWhiteSpace(regionName) && optionsStatic.CacheConfigurations != null)
            {
                configuration = optionsStatic.CacheConfigurations.FirstOrDefault(x => x.RegionName == regionName);
            }

            if (configuration == null)
            {
                log.DebugFormat("loading cache configuration for '{0}' from properties/defaults", regionName);
                configuration = RedisCacheConfiguration.FromPropertiesOrDefaults(regionName, properties);
            }

            return(BuildCache(configuration, properties, connectionMultiplexerStatic, optionsStatic));
        }
예제 #20
0
        public object Get(object key)
        {
            if (key == null)
            {
                return(null);
            }
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("fetching object {0} from the cache", key);
            }

            return(IndexusDistributionCache.SharedCache.Get(key.ToString()));
        }
        /// <summary>
        /// Configure the cache
        /// </summary>
        /// <param name="regionName">the name of the cache region</param>
        /// <param name="properties">configuration settings</param>
        /// <returns></returns>
        public ICache BuildCache(string regionName, IDictionary <string, string> properties)
        {
            //return a configured cache region if we have one for the region already
            //the only way this will really happen is if there is a query cache specified for a region that is configured
            //since query caches are not configured at session factory startup
            if (String.IsNullOrEmpty(regionName) == false && cacheRegions.ContainsKey(regionName))
            {
                return(cacheRegions[regionName]);
            }

            //build the cache from preconfigured values if the region has configuration values
            if (cacheRegionSettingsList != null)
            {
                CacheRegionElement regionSettings = cacheRegionSettingsList[regionName];

                if (regionSettings != null)
                {
                    SysCacheRegion cacheRegion;

                    lock (regionsSyncRoot)
                    {
                        //note that the only reason we have to do this double check is because the query cache
                        //can try to create caches at unpredictable times
                        if (cacheRegions.TryGetValue(regionName, out cacheRegion) == false)
                        {
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("building cache region, '{0}', from configuration", regionName);
                            }

                            //build the cache region with settings and put it into the list so that this proces will not occur again
                            cacheRegion = new SysCacheRegion(regionName, regionSettings, properties);
                            cacheRegions[regionName] = cacheRegion;
                        }
                    }

                    return(cacheRegion);
                }
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("building non-configured cache region : {0}", regionName);
            }

            //we will end up creating cache regions here for cache regions that nhibernate
            //uses internally and cache regions that weren't specified in the application config file
            return(new SysCacheRegion(regionName, properties));
        }
예제 #22
0
        public object Get(object key)
        {
            if (key == null)
            {
                return(null);
            }
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("fetching object {0} from the cache", key);
            }

            CacheItemVersion version = null;

            return(cache.Get(region, key.ToString(), ref version));
        }
예제 #23
0
        public static ISolution Build(Double fitness, ShiftMatrix m, int evaluatedSolutions, int numberOfItems)
        {
            var sw = new Stopwatch();

            sw.Start();

            var r = new int?[m.Days, m.Slots];

            for (int day = 0; day < m.Days; day++)
            {
                for (int slot = 0; slot < m.Slots; slot++)
                {
                    r[day, slot] = null;
                }
            }

            for (int day = 0; day < m.Days; day++)
            {
                for (int slot = 0; slot < m.Slots; slot++)
                {
                    r[day, slot] = m[day, slot].ChosenItem;
                }
            }

            sw.Stop();
            log.DebugFormat("Solution built in {0} ms", sw.ElapsedMilliseconds);

            return(new Solution(numberOfItems)
            {
                Fitness = fitness,
                Allocations = r,
                EvaluatedSolutions = evaluatedSolutions
            });
        }
예제 #24
0
        static MemCacheProvider()
        {
            log = LoggerProvider.LoggerFor((typeof(MemCacheProvider)));
            var configs = ConfigurationManager.GetSection("memcache") as MemCacheConfig[];

            if (configs != null)
            {
                var myWeights = new ArrayList();
                var myServers = new ArrayList();
                foreach (MemCacheConfig config in configs)
                {
                    myServers.Add(string.Format("{0}:{1}", config.Host, config.Port));
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("adding config for memcached on host {0}", config.Host);
                    }
                    if (config.Weight > 0)
                    {
                        myWeights.Add(config.Weight);
                    }
                }
                servers = (string[])myServers.ToArray(typeof(string));
                weights = (int[])myWeights.ToArray(typeof(int));
            }
        }
예제 #25
0
        /// <summary>
        /// Handles executing the login.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="assertion">The assertion.</param>
        private void DoSignOn(IOwinContext context, Saml20Assertion assertion)
        {
            context.Set("Saml2:assertion", assertion);
            var subject = assertion.Subject ?? new SAML2.Schema.Core.NameId();

            Logger.DebugFormat(TraceMessages.SignOnProcessed, assertion.SessionIndex, subject.Value, subject.Format);
        }
예제 #26
0
        /// <summary>
        /// Initializes the index at the given index
        /// </summary>
        protected FSDirectory InitializeIndex(DirectoryInfo path, string indexName = null)
        {
            try
            {
                var directory = FSDirectory.Open(path.FullName);

                // Exit if the index already exists
                if (IndexReader.IndexExists(directory))
                {
                    return(directory);
                }

                // TODO:RB: re-add logging
                log.DebugFormat("Initialize index: '{0}'", path);

                var maxFieldLength = IndexWriter.MaxFieldLength.UNLIMITED;
                var policy         = new KeepOnlyLastCommitDeletionPolicy();

                using (var analyzer = new StandardAnalyzer(Environment.LuceneVersion))
                    using (var indexWriter = new IndexWriter(directory, analyzer, true, policy, maxFieldLength))
                    {
                        // Do nothing, index writer's constructor has initialized the index
                        log.Info("Index writer called to create directory" + path.FullName);

                        indexWriter.Close();
                    }

                return(directory);
            }
            catch (IOException e)
            {
                throw new HibernateException("Unable to initialize index: " + indexName ?? path.FullName, e);
            }
        }
예제 #27
0
 /// <summary>
 /// If debug logging is enabled, log a string such as "msg: expression.ToString()".
 /// </summary>
 internal static void LogExpression(string msg, Expression expression)
 {
     if (Log.IsDebugEnabled)
     {
         Log.DebugFormat("{0}: {1}", msg, expression.ToString());
     }
 }
예제 #28
0
        public object ExecuteWithChanges(
            DbCommand cmd,
            string entityName,
            EntityChangeType changeType,
            Func <string> changeDescriber = null)
        {
            _log.DebugFormat("Executing command: \r\n {0}", cmd.CommandText);
            object result;

            using (var conn = DB.OpenConnection())
                using (var tx = conn.BeginTransaction())
                {
                    try
                    {
                        cmd.Connection  = conn;
                        cmd.Transaction = tx;
                        result          = cmd.ExecuteScalar();

                        if (result != null)
                        {
                            if (Admin.IsChangesEnabled)
                            {
                                var changeCmd = CreateChangeCommand(entityName, changeType, result.ToString(), changeDescriber);
                                _log.DebugFormat("Executing change command: \r\n {0}", changeCmd.CommandText);
                                changeCmd.Connection  = conn;
                                changeCmd.Transaction = tx;
                                changeCmd.ExecuteNonQuery();
                            }

                            _log.Debug("Commit transaction");
                            tx.Commit();
                        }
                        else
                        {
                            Rollback(tx);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                        Rollback(tx);
                        throw;
                    }
                }

            return(result);
        }
        /// <summary> Constructs a new AbstractEntityTuplizer instance. </summary>
        /// <param name="entityMetamodel">The "interpreted" information relating to the mapped entity. </param>
        /// <param name="mappingInfo">The parsed "raw" mapping data relating to the given entity. </param>
        protected AbstractEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo)
        {
            this.entityMetamodel = entityMetamodel;

            if (!entityMetamodel.IdentifierProperty.IsVirtual)
            {
                idGetter = BuildPropertyGetter(mappingInfo.IdentifierProperty, mappingInfo);
                idSetter = BuildPropertySetter(mappingInfo.IdentifierProperty, mappingInfo);
            }
            else
            {
                idGetter = null;
                idSetter = null;
            }

            propertySpan = entityMetamodel.PropertySpan;

            getters = new IGetter[propertySpan];
            setters = new ISetter[propertySpan];

            bool foundCustomAccessor = false;
            int  i = 0;

            foreach (Mapping.Property property in mappingInfo.PropertyClosureIterator)
            {
                getters[i] = BuildPropertyGetter(property, mappingInfo);
                setters[i] = BuildPropertySetter(property, mappingInfo);
                if (!property.IsBasicPropertyAccessor)
                {
                    foundCustomAccessor = true;
                }
                i++;
            }
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("{0} accessors found for entity: {1}", foundCustomAccessor ? "Custom" : "No custom",
                                mappingInfo.EntityName);
            }
            hasCustomAccessors = foundCustomAccessor;

            //NH-1587
            //instantiator = BuildInstantiator(mappingInfo);

            if (entityMetamodel.IsLazy)
            {
                proxyFactory = BuildProxyFactory(mappingInfo, idGetter, idSetter);
                if (proxyFactory == null)
                {
                    entityMetamodel.IsLazy = false;
                }
            }
            else
            {
                proxyFactory = null;
            }

            Mapping.Component mapper = mappingInfo.IdentifierMapper;
            identifierMapperType = mapper == null ? null : (IAbstractComponentType)mapper.Type;
        }
예제 #30
0
        /// <summary>
        /// Used in the cases where <see cref="DetermineSegmentValue"/> is unable to
        /// determine the value to use.
        /// </summary>
        protected string DetermineDefaultSegmentValue(IDictionary <string, string> parms)
        {
            bool   preferSegmentPerEntity = PropertiesHelper.GetBoolean(ConfigPreferSegmentPerEntity, parms, false);
            string defaultToUse           = preferSegmentPerEntity ? parms[PersistentIdGeneratorParmsNames.Table] : DefaultSegmentValue;

            log.DebugFormat("Explicit segment value for id generator [{0}.{1}] suggested; using default [{2}].", TableName, SegmentColumnName, defaultToUse);

            return(defaultToUse);
        }
 static MemCacheProvider()
 {
     log = LoggerProvider.LoggerFor((typeof(MemCacheProvider)));
     var configs = ConfigurationManager.GetSection("memcache") as MemCacheConfig[];
     if (configs != null)
     {
         var myWeights = new ArrayList();
         var myServers = new ArrayList();
         foreach (MemCacheConfig config in configs)
         {
             myServers.Add(string.Format("{0}:{1}", config.Host, config.Port));
             if (log.IsDebugEnabled)
             {
                 log.DebugFormat("adding config for memcached on host {0}", config.Host);
             }
             if (config.Weight > 0)
             {
                 myWeights.Add(config.Weight);
             }
         }
         servers = (string[]) myServers.ToArray(typeof (string));
         weights = (int[]) myWeights.ToArray(typeof (int));
     }
 }