/// <summary>
        /// 输出结果
        /// </summary>
        /// <param name="context"></param>
        public void Ouput(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);


            if (MaxAge > 0)
            {
                context.Response.Cache.AppendCacheExtension("max-age=" + MaxAge.ToString());
            }

            if (LastModified.Year > 2000)
            {
                context.Response.Cache.SetLastModified(LastModified);
            }

            if (string.IsNullOrEmpty(ETag) == false)
            {
                context.Response.Cache.SetETag(ETag);
            }



            ActionExecutor.OutputActionResult(context, Result);
        }
Exemple #2
0
        public override int GetHashCode()
        {
            int hc = 29;

            unchecked {
                hc = hc * 29 + HashCodeCalculator.Calculate(extensions);
                hc = hc * 29 + MaxAge.GetHashCode();
                hc = hc * 29 + MaxStale.GetHashCode();
                hc = hc * 29 + MaxStaleLimit.GetHashCode();
                hc = hc * 29 + MinFresh.GetHashCode();
                hc = hc * 29 + MustRevalidate.GetHashCode();
                hc = hc * 29 + HashCodeCalculator.Calculate(no_cache_headers);
                hc = hc * 29 + NoCache.GetHashCode();
                hc = hc * 29 + NoStore.GetHashCode();
                hc = hc * 29 + NoTransform.GetHashCode();
                hc = hc * 29 + OnlyIfCached.GetHashCode();
                hc = hc * 29 + Private.GetHashCode();
                hc = hc * 29 + HashCodeCalculator.Calculate(private_headers);
                hc = hc * 29 + ProxyRevalidate.GetHashCode();
                hc = hc * 29 + Public.GetHashCode();
                hc = hc * 29 + SharedMaxAge.GetHashCode();
            }

            return(hc);
        }
Exemple #3
0
        public GenericAsset GetAsset(Xid id, Xid requestingNodeId, MaxAge maxAge)
        {
            // Convert to a many lookup
            var result = GetAssets(new List<Xid>() { id }, requestingNodeId, maxAge);

            // Return object
            return result.Assets.First();
        }
Exemple #4
0
 /// <summary>
 /// Checks if the current WebCookie is equal to the provided one.
 /// </summary>
 /// <param name="other">The instance to compare to.</param>
 /// <returns>True if both are value-wise equal, otherwise false.</returns>
 public Boolean Equals(WebCookie other) =>
 Domain.Equals(other.Domain) &&
 Expires.Equals(other.Expires) &&
 IsHostOnly.Equals(other.IsHostOnly) &&
 IsHttpOnly.Equals(other.IsHttpOnly) &&
 IsSecure.Equals(other.IsSecure) &&
 Key.Equals(other.Key) &&
 Value.Equals(other.Value) &&
 Path.Equals(other.Path) &&
 MaxAge.Equals(other.MaxAge);
Exemple #5
0
 public override int GetHashCode()
 {
     return(StringComparer.OrdinalIgnoreCase.GetHashCode(_name)
            ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_value)
            ^ (Expires.HasValue ? Expires.GetHashCode() : 0)
            ^ (MaxAge.HasValue ? MaxAge.GetHashCode() : 0)
            ^ (Domain != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(Domain) : 0)
            ^ (Path != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(Path) : 0)
            ^ Secure.GetHashCode()
            ^ HttpOnly.GetHashCode());
 }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (ETag != null ? ETag.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ MaxAge.GetHashCode();
         hashCode = (hashCode * 397) ^ Expires.GetHashCode();
         hashCode = (hashCode * 397) ^ LastModified.GetHashCode();
         hashCode = (hashCode * 397) ^ CacheControl.GetHashCode();
         return(hashCode);
     }
 }
Exemple #7
0
        internal GenericAsset(Variant variant, Xid id, Xid requestingNodeId, MaxAge maxAge)
        {
            Variant = variant;
            DataSet = variant.DataSet;
            Cache = variant.Cache;
            Schema = variant.Schema;

            Id = id;
            RequestingNodeId = requestingNodeId;

            // Load record
            Reload(maxAge);
        }
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var isLocal      = filterContext.HttpContext.Request.IsLocal && !DisableLocal;
        var originHeader =
            filterContext.HttpContext.Request.Headers.Get(IncomingOriginHeader);
        var response = filterContext.HttpContext.Response;

        if (!String.IsNullOrWhiteSpace(originHeader) &&
            (isLocal || IsAllowedOrigin(originHeader)))
        {
            response.AddHeader(OutgoingOriginHeader, originHeader);
            response.AddHeader(OutgoingMethodsHeader, AllowedMethods);
            response.AddHeader(OutgoingAgeHeader, MaxAge.ToString());
        }
    }
Exemple #9
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Name != null ? Name.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Value != null ? Value.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Path != null ? Path.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Secure.GetHashCode();
         hashCode = (hashCode * 397) ^ HttpOnly.GetHashCode();
         hashCode = (hashCode * 397) ^ (Domain != null ? Domain.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Expires.GetHashCode();
         hashCode = (hashCode * 397) ^ MaxAge.GetHashCode();
         hashCode = (hashCode * 397) ^ (int)SameSite;
         return(hashCode);
     }
 }
 public bool Equals(CacheRequestBase other)
 {
     if (ReferenceEquals(null, other))
     {
         return(false);
     }
     if (ReferenceEquals(this, other))
     {
         return(true);
     }
     return(string.Equals(ETag, other.ETag) &&
            MaxAge.Equals(other.MaxAge) &&
            Expires.Equals(other.Expires) &&
            LastModified.Equals(other.LastModified) &&
            CacheControl == other.CacheControl);
 }
Exemple #11
0
        public override bool Equals(object obj)
        {
            var other = obj as SetCookieHeaderValue;

            if (other == null)
            {
                return(false);
            }

            return(string.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase) &&
                   string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase) &&
                   Expires.Equals(other.Expires) &&
                   MaxAge.Equals(other.MaxAge) &&
                   string.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase) &&
                   string.Equals(Path, other.Path, StringComparison.OrdinalIgnoreCase) &&
                   Secure == other.Secure &&
                   HttpOnly == other.HttpOnly);
        }
        public override int GetHashCode()
        {
            var hash = StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_name)
                       ^ StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(_value)
                       ^ (Expires.HasValue ? Expires.GetHashCode() : 0)
                       ^ (MaxAge.HasValue ? MaxAge.GetHashCode() : 0)
                       ^ (Domain != null ? StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(Domain) : 0)
                       ^ (Path != null ? StringSegmentComparer.OrdinalIgnoreCase.GetHashCode(Path) : 0)
                       ^ Secure.GetHashCode()
                       ^ SameSite.GetHashCode()
                       ^ HttpOnly.GetHashCode();

            foreach (var extension in Extensions)
            {
                hash ^= extension.GetHashCode();
            }

            return(hash);
        }
        public override bool Equals(object?obj)
        {
            var other = obj as SetCookieHeaderValue;

            if (other == null)
            {
                return(false);
            }

            return(StringSegment.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase) &&
                   StringSegment.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase) &&
                   Expires.Equals(other.Expires) &&
                   MaxAge.Equals(other.MaxAge) &&
                   StringSegment.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase) &&
                   StringSegment.Equals(Path, other.Path, StringComparison.OrdinalIgnoreCase) &&
                   Secure == other.Secure &&
                   SameSite == other.SameSite &&
                   HttpOnly == other.HttpOnly &&
                   HeaderUtilities.AreEqualCollections(Extensions, other.Extensions, StringSegmentComparer.OrdinalIgnoreCase));
        }
Exemple #14
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ruleCase_ == RuleOneofCase.MaxNumVersions)
            {
                hash ^= MaxNumVersions.GetHashCode();
            }
            if (ruleCase_ == RuleOneofCase.MaxAge)
            {
                hash ^= MaxAge.GetHashCode();
            }
            if (ruleCase_ == RuleOneofCase.Intersection)
            {
                hash ^= Intersection.GetHashCode();
            }
            if (ruleCase_ == RuleOneofCase.Union)
            {
                hash ^= Union.GetHashCode();
            }
            return(hash);
        }
        /// <summary>
        /// 输出结果
        /// </summary>
        /// <param name="context"></param>
        public void Ouput(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);


            if (MaxAge > 0)
            {
                context.Response.Cache.AppendCacheExtension("max-age=" + MaxAge.ToString());
            }

            // LastModified 可以不设置,那么就是默认值:DateTime.MinValue
            // 判断的意思是:如果设置了LastModified,就调用 SetLastModified
            if (LastModified.Year > 2000)
            {
                context.Response.Cache.SetLastModified(LastModified);
            }

            if (string.IsNullOrEmpty(ETag) == false)
            {
                context.Response.Cache.SetETag(ETag);
            }


            // 找回与当前请求有关的ActionExecutor实例。
            ActionHandler handler = context.Handler as ActionHandler;

            if (handler == null)
            {
                throw new InvalidOperationException("HttpCacheResult只能与ActionHandler一起配合使用。");
            }

            // 输出内部对象
            handler.ActionExecutor.ExecuteProcessResult(this.Result);
        }
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage   = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "agerange",
            };
            var dates = new List <string>
            {
                MinAge.ToString(),
                MaxAge.ToString()
            };
            var errorMessages = new List <string>
            {
                MinAgeErrorMessage,
                MaxAgeErrorMessage,
                InvalidErrorMessage
            };

            rule.ValidationParameters.Add("dates", dates.ToConcatenatedString(" "));
            rule.ValidationParameters.Add("errormessages", errorMessages.ToConcatenatedString());
            yield return(rule);
        }
Exemple #17
0
        public ResultantAssets GetAssets(IEnumerable<Xid> ids, Xid requestingNodeId, MaxAge maxAge)
        {
            if (null == ids) {
                throw new ArgumentNullException("ids");
            }
            if ((int)maxAge < -2) {
                throw new ArgumentOutOfRangeException("maxAge", "must be at least -2"); // -1 means infinate, -2 means noload
            }

            var pending = new HashSet<Xid>(ids);

            // Fetch from cache
            if (maxAge == MaxAge.Any || (int)maxAge > 0) {
                foreach (var record in GenericAsset.GetFromCache(Variant, pending, maxAge)) {
                    pending.Remove(record.Id);
                }
            }

            // Cache any remaining items
            if (pending.Count > 0) {
                foreach (var record in GenericAsset.GetFromDatabase(Variant, pending)) {
                    pending.Remove(record.Id);
                }
            }

            // Add nodes to output
            var output = new List<GenericAsset>(ids.Select(id => new GenericAsset(Variant, id, requestingNodeId, MaxAge.Any)));

            // Add non-existant nodes to output
            foreach (var id in pending) {
                var node = new GenericAsset(Variant, id, requestingNodeId, MaxAge.NoLoad);
                node.SetExists(false);
                output.Add(node);
            }

            return new ResultantAssets(output, maxAge);
        }
        /// <summary>
        /// Applies this rule's properties to the provided HttpContext. If the context indicates that this is a
        /// preflight request, the response will be immediately completed and returned.
        /// </summary>
        /// <param name="context">The HttpContext to alter.</param>
        public void Apply(HttpContext context)
        {
            var origin = ((Uri)context.Items["Rhythm.Cors.OriginUrl"]);

            if (this.Policy == "ALLOW")
            {
                // set the Allow-Origin header appropriately

                if (Domain == "*")
                {
                    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                }
                else
                {
                    context.Response.Headers.Add("Access-Control-Allow-Origin", origin.OriginalString);
                    var varyHeaderValue = context.Response.Headers["Vary"];
                    if (!String.IsNullOrWhiteSpace(varyHeaderValue))
                    {
                        varyHeaderValue += ", ";
                    }
                    else
                    {
                        varyHeaderValue = "";
                    }
                    varyHeaderValue += "Origin";
                    context.Response.Headers["Vary"] = varyHeaderValue;
                }

                // add additional CORS header properties

                if (!String.IsNullOrWhiteSpace(ExposeHeaders))
                {
                    context.Response.Headers["Access-Control-Expose-Headers"] = ExposeHeaders;
                }

                if (AllowCredentials.HasValue)
                {
                    context.Response.Headers["Access-Control-Allow-Credentials"] = AllowCredentials.Value.ToString().ToLower();
                }

                // if this is a preflight request, return the response immediately

                if (context.Request.HttpMethod == "OPTIONS")
                {
                    var requestMethod  = context.Request.Headers["Access-Control-Request-Method"];
                    var requestHeaders = context.Request.Headers["Access-Control-Request-Headers"];

                    if (!String.IsNullOrWhiteSpace(AllowMethods))
                    {
                        context.Response.Headers["Access-Control-Allow-Methods"] = AllowMethods;
                    }

                    if (!String.IsNullOrWhiteSpace(AllowHeaders))
                    {
                        context.Response.Headers["Access-Control-Allow-Headers"] = AllowHeaders;
                    }

                    if (MaxAge.HasValue)
                    {
                        context.Response.Headers["Access-Control-Max-Age"] = MaxAge.ToString();
                    }

                    context.Response.StatusCode        = 204;
                    context.Response.StatusDescription = "NO CONTENT";
                    context.Response.End();
                }
            }
        }
 internal ResultantNodeIds(IEnumerable<Xid> nodeIds, MaxAge maxAge)
 {
     NodeIdsInternal = new List<Xid>(nodeIds);
     MaxAge = maxAge;
     AsAt = DateTime.Now;
 }
Exemple #20
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (DatasourceName != null)
         {
             hashCode = hashCode * 59 + DatasourceName.GetHashCode();
         }
         if (DatasourceSvcPropName != null)
         {
             hashCode = hashCode * 59 + DatasourceSvcPropName.GetHashCode();
         }
         if (DriverClassName != null)
         {
             hashCode = hashCode * 59 + DriverClassName.GetHashCode();
         }
         if (Url != null)
         {
             hashCode = hashCode * 59 + Url.GetHashCode();
         }
         if (Username != null)
         {
             hashCode = hashCode * 59 + Username.GetHashCode();
         }
         if (Password != null)
         {
             hashCode = hashCode * 59 + Password.GetHashCode();
         }
         if (DefaultAutoCommit != null)
         {
             hashCode = hashCode * 59 + DefaultAutoCommit.GetHashCode();
         }
         if (DefaultReadOnly != null)
         {
             hashCode = hashCode * 59 + DefaultReadOnly.GetHashCode();
         }
         if (DefaultTransactionIsolation != null)
         {
             hashCode = hashCode * 59 + DefaultTransactionIsolation.GetHashCode();
         }
         if (DefaultCatalog != null)
         {
             hashCode = hashCode * 59 + DefaultCatalog.GetHashCode();
         }
         if (MaxActive != null)
         {
             hashCode = hashCode * 59 + MaxActive.GetHashCode();
         }
         if (MaxIdle != null)
         {
             hashCode = hashCode * 59 + MaxIdle.GetHashCode();
         }
         if (MinIdle != null)
         {
             hashCode = hashCode * 59 + MinIdle.GetHashCode();
         }
         if (InitialSize != null)
         {
             hashCode = hashCode * 59 + InitialSize.GetHashCode();
         }
         if (MaxWait != null)
         {
             hashCode = hashCode * 59 + MaxWait.GetHashCode();
         }
         if (MaxAge != null)
         {
             hashCode = hashCode * 59 + MaxAge.GetHashCode();
         }
         if (TestOnBorrow != null)
         {
             hashCode = hashCode * 59 + TestOnBorrow.GetHashCode();
         }
         if (TestOnReturn != null)
         {
             hashCode = hashCode * 59 + TestOnReturn.GetHashCode();
         }
         if (TestWhileIdle != null)
         {
             hashCode = hashCode * 59 + TestWhileIdle.GetHashCode();
         }
         if (ValidationQuery != null)
         {
             hashCode = hashCode * 59 + ValidationQuery.GetHashCode();
         }
         if (ValidationQueryTimeout != null)
         {
             hashCode = hashCode * 59 + ValidationQueryTimeout.GetHashCode();
         }
         if (TimeBetweenEvictionRunsMillis != null)
         {
             hashCode = hashCode * 59 + TimeBetweenEvictionRunsMillis.GetHashCode();
         }
         if (MinEvictableIdleTimeMillis != null)
         {
             hashCode = hashCode * 59 + MinEvictableIdleTimeMillis.GetHashCode();
         }
         if (ConnectionProperties != null)
         {
             hashCode = hashCode * 59 + ConnectionProperties.GetHashCode();
         }
         if (InitSQL != null)
         {
             hashCode = hashCode * 59 + InitSQL.GetHashCode();
         }
         if (JdbcInterceptors != null)
         {
             hashCode = hashCode * 59 + JdbcInterceptors.GetHashCode();
         }
         if (ValidationInterval != null)
         {
             hashCode = hashCode * 59 + ValidationInterval.GetHashCode();
         }
         if (LogValidationErrors != null)
         {
             hashCode = hashCode * 59 + LogValidationErrors.GetHashCode();
         }
         if (DatasourceSvcProperties != null)
         {
             hashCode = hashCode * 59 + DatasourceSvcProperties.GetHashCode();
         }
         return(hashCode);
     }
 }
Exemple #21
0
        /// <summary>
        /// Returns true if OrgApacheSlingDatasourceDataSourceFactoryProperties instances are equal
        /// </summary>
        /// <param name="other">Instance of OrgApacheSlingDatasourceDataSourceFactoryProperties to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(OrgApacheSlingDatasourceDataSourceFactoryProperties other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     DatasourceName == other.DatasourceName ||
                     DatasourceName != null &&
                     DatasourceName.Equals(other.DatasourceName)
                     ) &&
                 (
                     DatasourceSvcPropName == other.DatasourceSvcPropName ||
                     DatasourceSvcPropName != null &&
                     DatasourceSvcPropName.Equals(other.DatasourceSvcPropName)
                 ) &&
                 (
                     DriverClassName == other.DriverClassName ||
                     DriverClassName != null &&
                     DriverClassName.Equals(other.DriverClassName)
                 ) &&
                 (
                     Url == other.Url ||
                     Url != null &&
                     Url.Equals(other.Url)
                 ) &&
                 (
                     Username == other.Username ||
                     Username != null &&
                     Username.Equals(other.Username)
                 ) &&
                 (
                     Password == other.Password ||
                     Password != null &&
                     Password.Equals(other.Password)
                 ) &&
                 (
                     DefaultAutoCommit == other.DefaultAutoCommit ||
                     DefaultAutoCommit != null &&
                     DefaultAutoCommit.Equals(other.DefaultAutoCommit)
                 ) &&
                 (
                     DefaultReadOnly == other.DefaultReadOnly ||
                     DefaultReadOnly != null &&
                     DefaultReadOnly.Equals(other.DefaultReadOnly)
                 ) &&
                 (
                     DefaultTransactionIsolation == other.DefaultTransactionIsolation ||
                     DefaultTransactionIsolation != null &&
                     DefaultTransactionIsolation.Equals(other.DefaultTransactionIsolation)
                 ) &&
                 (
                     DefaultCatalog == other.DefaultCatalog ||
                     DefaultCatalog != null &&
                     DefaultCatalog.Equals(other.DefaultCatalog)
                 ) &&
                 (
                     MaxActive == other.MaxActive ||
                     MaxActive != null &&
                     MaxActive.Equals(other.MaxActive)
                 ) &&
                 (
                     MaxIdle == other.MaxIdle ||
                     MaxIdle != null &&
                     MaxIdle.Equals(other.MaxIdle)
                 ) &&
                 (
                     MinIdle == other.MinIdle ||
                     MinIdle != null &&
                     MinIdle.Equals(other.MinIdle)
                 ) &&
                 (
                     InitialSize == other.InitialSize ||
                     InitialSize != null &&
                     InitialSize.Equals(other.InitialSize)
                 ) &&
                 (
                     MaxWait == other.MaxWait ||
                     MaxWait != null &&
                     MaxWait.Equals(other.MaxWait)
                 ) &&
                 (
                     MaxAge == other.MaxAge ||
                     MaxAge != null &&
                     MaxAge.Equals(other.MaxAge)
                 ) &&
                 (
                     TestOnBorrow == other.TestOnBorrow ||
                     TestOnBorrow != null &&
                     TestOnBorrow.Equals(other.TestOnBorrow)
                 ) &&
                 (
                     TestOnReturn == other.TestOnReturn ||
                     TestOnReturn != null &&
                     TestOnReturn.Equals(other.TestOnReturn)
                 ) &&
                 (
                     TestWhileIdle == other.TestWhileIdle ||
                     TestWhileIdle != null &&
                     TestWhileIdle.Equals(other.TestWhileIdle)
                 ) &&
                 (
                     ValidationQuery == other.ValidationQuery ||
                     ValidationQuery != null &&
                     ValidationQuery.Equals(other.ValidationQuery)
                 ) &&
                 (
                     ValidationQueryTimeout == other.ValidationQueryTimeout ||
                     ValidationQueryTimeout != null &&
                     ValidationQueryTimeout.Equals(other.ValidationQueryTimeout)
                 ) &&
                 (
                     TimeBetweenEvictionRunsMillis == other.TimeBetweenEvictionRunsMillis ||
                     TimeBetweenEvictionRunsMillis != null &&
                     TimeBetweenEvictionRunsMillis.Equals(other.TimeBetweenEvictionRunsMillis)
                 ) &&
                 (
                     MinEvictableIdleTimeMillis == other.MinEvictableIdleTimeMillis ||
                     MinEvictableIdleTimeMillis != null &&
                     MinEvictableIdleTimeMillis.Equals(other.MinEvictableIdleTimeMillis)
                 ) &&
                 (
                     ConnectionProperties == other.ConnectionProperties ||
                     ConnectionProperties != null &&
                     ConnectionProperties.Equals(other.ConnectionProperties)
                 ) &&
                 (
                     InitSQL == other.InitSQL ||
                     InitSQL != null &&
                     InitSQL.Equals(other.InitSQL)
                 ) &&
                 (
                     JdbcInterceptors == other.JdbcInterceptors ||
                     JdbcInterceptors != null &&
                     JdbcInterceptors.Equals(other.JdbcInterceptors)
                 ) &&
                 (
                     ValidationInterval == other.ValidationInterval ||
                     ValidationInterval != null &&
                     ValidationInterval.Equals(other.ValidationInterval)
                 ) &&
                 (
                     LogValidationErrors == other.LogValidationErrors ||
                     LogValidationErrors != null &&
                     LogValidationErrors.Equals(other.LogValidationErrors)
                 ) &&
                 (
                     DatasourceSvcProperties == other.DatasourceSvcProperties ||
                     DatasourceSvcProperties != null &&
                     DatasourceSvcProperties.Equals(other.DatasourceSvcProperties)
                 ));
        }
Exemple #22
0
        public ResultantNodes GetNodes(IEnumerable<Xid> ids, Xid requestingNodeId, MaxAge maxAge)
        {
            if (null == ids) {
                throw new ArgumentNullException("ids");
            }
            if ((int)maxAge < -2) {
                throw new ArgumentOutOfRangeException("maxAge", "must be at least -2"); // -1 means infinate, -2 means noload
            }

            var output = new List<GenericNode>();
            var pending = new HashSet<Xid>(ids);

            // If we want to load...
            if (maxAge != MaxAge.NoLoad) {
                // Fetch from cache
                if ((int)maxAge > 0) {
                    foreach (var record in GenericNode.GetFromCache(Variant, pending, maxAge)) {
                        pending.Remove(record.Id);
                    }
                }

                // Cache any remaining items
                if (pending.Count > 0) {
                    foreach (var record in GenericNode.GetFromDatabase(Variant, pending)) {
                        pending.Remove(record.Id);
                    }
                }

                // Add nodes to output
                output.AddRange(ids.Select(id => new GenericNode(Variant, id, requestingNodeId, MaxAge.Any)));
            }

            // Add non-existant nodes to output
            foreach (var id in pending) {
                var node = new GenericNode(Variant, id, requestingNodeId, MaxAge.NoLoad);
                // TODO: We know that this is non-existant - save a server call?
                output.Add(node);
            }

            return new ResultantNodes(output, maxAge);
        }
Exemple #23
0
        public ResultantNodes SearchNodes(Where where, Xid requestingNodeId, MaxAge maxAgeQuery, MaxAge maxAgeObjects)
        {
            if (null == where) {
                throw new ArgumentNullException("where");
            }

            // Get SQL string
            var sql = where.ToString();
            var sqlHash = SHA1.HashAsHexString(sql);

            // If cache is allowed - look it up
            if (maxAgeQuery > 0 || maxAgeQuery == MaxAge.Any) {
                // Calculate the oldest time this could be
                var oldestTime = DateTime.Now.AddMinutes(-(int)maxAgeQuery);

                // Load relevant query from cache
                lock (Cache) {
                    var cacheOutput = Cache.Get("query-" + sqlHash) as ResultantNodeIds;

                    // Check for cache hit
                    if (null != cacheOutput && cacheOutput.AsAt >= oldestTime || maxAgeQuery == MaxAge.Any) {
                        // Hit - return result
                        return GetNodes(cacheOutput.NodeIds, requestingNodeId, maxAgeObjects);
                    }
                }
            }

            // Open database
            var ids = new List<Xid>();

            // Fetch Ids
            using (var query = new DatabaseQuery(DatabaseQueryString.Create(where.ToString()))) {
                using(var rdr = query.ExecuteReader()){
                    while (rdr.Read()) {
                        ids.Add(new Xid((Guid)rdr[0]));
                    }
                }
            }

            // Create ID result
            var resultIds = new ResultantNodeIds(ids, maxAgeQuery);

            // Add items to cache
            lock (Cache) {
                Cache.Set("query-" + sqlHash, resultIds, Variant.GetCacheStoragePolicy());
            }

            return GetNodes(resultIds.NodeIds, requestingNodeId, maxAgeObjects);
        }
 internal ResultantAssetIds(IEnumerable<Xid> assetIds, MaxAge maxAge)
 {
     AssetIdsInternal = new List<Xid>(assetIds);
     MaxAge = maxAge;
     AsAt = DateTime.Now;
 }
        /// <summary>
        /// Append string representation of this <see cref="SetCookieHeaderValue"/> to given
        /// <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">
        /// The <see cref="StringBuilder"/> to receive the string representation of this
        /// <see cref="SetCookieHeaderValue"/>.
        /// </param>
        public void AppendToStringBuilder(StringBuilder builder)
        {
            builder.Append(_name.AsSpan());
            builder.Append("=");
            builder.Append(_value.AsSpan());

            if (Expires.HasValue)
            {
                AppendSegment(builder, ExpiresToken, HeaderUtilities.FormatDate(Expires.GetValueOrDefault()));
            }

            if (MaxAge.HasValue)
            {
                AppendSegment(builder, MaxAgeToken, HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds));
            }

            if (Domain != null)
            {
                AppendSegment(builder, DomainToken, Domain);
            }

            if (Path != null)
            {
                AppendSegment(builder, PathToken, Path);
            }

            if (Secure)
            {
                AppendSegment(builder, SecureToken, null);
            }

            // Allow for Unspecified (-1) to skip SameSite
            if (SameSite == SameSiteMode.None)
            {
                AppendSegment(builder, SameSiteToken, SameSiteNoneToken);
            }
            else if (SameSite == SameSiteMode.Lax)
            {
                AppendSegment(builder, SameSiteToken, SameSiteLaxToken);
            }
            else if (SameSite == SameSiteMode.Strict)
            {
                AppendSegment(builder, SameSiteToken, SameSiteStrictToken);
            }

            if (HttpOnly)
            {
                AppendSegment(builder, HttpOnlyToken, null);
            }
        }
        // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={strict|lax|none}; httponly
        public override string ToString()
        {
            var length = _name.Length + EqualsToken.Length + _value.Length;

            string maxAge   = null;
            string sameSite = null;

            if (Expires.HasValue)
            {
                length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + ExpiresDateLength;
            }

            if (MaxAge.HasValue)
            {
                maxAge  = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds);
                length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length;
            }

            if (Domain != null)
            {
                length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length;
            }

            if (Path != null)
            {
                length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length;
            }

            if (Secure)
            {
                length += SeparatorToken.Length + SecureToken.Length;
            }

            // Allow for Unspecified (-1) to skip SameSite
            if (SameSite == SameSiteMode.None)
            {
                sameSite = SameSiteNoneToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }
            else if (SameSite == SameSiteMode.Lax)
            {
                sameSite = SameSiteLaxToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }
            else if (SameSite == SameSiteMode.Strict)
            {
                sameSite = SameSiteStrictToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }

            if (HttpOnly)
            {
                length += SeparatorToken.Length + HttpOnlyToken.Length;
            }

            return(string.Create(length, (this, maxAge, sameSite), (span, tuple) =>
            {
                var(headerValue, maxAgeValue, sameSite) = tuple;

                Append(ref span, headerValue._name);
                Append(ref span, EqualsToken);
                Append(ref span, headerValue._value);

                if (headerValue.Expires is DateTimeOffset expiresValue)
                {
                    Append(ref span, SeparatorToken);
                    Append(ref span, ExpiresToken);
                    Append(ref span, EqualsToken);

                    var formatted = expiresValue.TryFormat(span, out var charsWritten, ExpiresDateFormat);
                    span = span.Slice(charsWritten);

                    Debug.Assert(formatted);
                }

                if (maxAgeValue != null)
                {
                    AppendSegment(ref span, MaxAgeToken, maxAgeValue);
                }

                if (headerValue.Domain != null)
                {
                    AppendSegment(ref span, DomainToken, headerValue.Domain);
                }

                if (headerValue.Path != null)
                {
                    AppendSegment(ref span, PathToken, headerValue.Path);
                }

                if (headerValue.Secure)
                {
                    AppendSegment(ref span, SecureToken, null);
                }

                if (sameSite != null)
                {
                    AppendSegment(ref span, SameSiteToken, sameSite);
                }

                if (headerValue.HttpOnly)
                {
                    AppendSegment(ref span, HttpOnlyToken, null);
                }
            }));
        }
Exemple #27
0
 public HstsOptionsBuilder SetMaxAge(MaxAge maxAge)
 {
     this.options.MaxAge = maxAge;
     return(this);
 }
Exemple #28
0
        // name="value"; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly
        public override string ToString()
        {
            var length = _name.Length + EqualsToken.Length + _value.Length;

            string expires  = null;
            string maxAge   = null;
            string sameSite = null;

            if (Expires.HasValue)
            {
                expires = HeaderUtilities.FormatDate(Expires.GetValueOrDefault());
                length += SeparatorToken.Length + ExpiresToken.Length + EqualsToken.Length + expires.Length;
            }

            if (MaxAge.HasValue)
            {
                maxAge  = HeaderUtilities.FormatNonNegativeInt64((long)MaxAge.GetValueOrDefault().TotalSeconds);
                length += SeparatorToken.Length + MaxAgeToken.Length + EqualsToken.Length + maxAge.Length;
            }

            if (Domain != null)
            {
                length += SeparatorToken.Length + DomainToken.Length + EqualsToken.Length + Domain.Length;
            }

            if (Path != null)
            {
                length += SeparatorToken.Length + PathToken.Length + EqualsToken.Length + Path.Length;
            }

            if (Secure)
            {
                length += SeparatorToken.Length + SecureToken.Length;
            }

            if (SameSite != SameSiteMode.None)
            {
                sameSite = SameSite == SameSiteMode.Lax ? SameSiteLaxToken : SameSiteStrictToken;
                length  += SeparatorToken.Length + SameSiteToken.Length + EqualsToken.Length + sameSite.Length;
            }

            if (HttpOnly)
            {
                length += SeparatorToken.Length + HttpOnlyToken.Length;
            }

            var sb = new InplaceStringBuilder(length);

            sb.Append(_name);
            sb.Append(EqualsToken);
            sb.Append(_value);

            if (expires != null)
            {
                AppendSegment(ref sb, ExpiresToken, expires);
            }

            if (maxAge != null)
            {
                AppendSegment(ref sb, MaxAgeToken, maxAge);
            }

            if (Domain != null)
            {
                AppendSegment(ref sb, DomainToken, Domain);
            }

            if (Path != null)
            {
                AppendSegment(ref sb, PathToken, Path);
            }

            if (Secure)
            {
                AppendSegment(ref sb, SecureToken, null);
            }

            if (SameSite != SameSiteMode.None)
            {
                AppendSegment(ref sb, SameSiteToken, sameSite);
            }

            if (HttpOnly)
            {
                AppendSegment(ref sb, HttpOnlyToken, null);
            }

            return(sb.ToString());
        }
Exemple #29
0
        public GenericAsset Reload(MaxAge maxAge)
        {
            lock (this) {
                if (maxAge == MaxAge.NoLoad) {
                    return this;
                }

                // Try and load from cache
                if (null == (Record = GetFromCache(Variant, new List<Xid>() { Id }, maxAge).FirstOrDefault())) {
                    // Try and load from database
                    if (null == (Record = GetFromDatabase(Variant, new List<Xid>() { Id }).FirstOrDefault())) {
                        // Record not found - abort
                        Exists = false;
                        return this;
                    }
                }

                // Mark as existing
                Exists = true;
            }

            return this;
        }
Exemple #30
0
        internal static IEnumerable<ARecord> GetFromCache(Variant variant, IEnumerable<Xid> ids, MaxAge maxAge)
        {
            if (null == ids) {
                throw new ArgumentNullException("ids");
            }

            var output = new List<ARecord>();

            // Calculate the oldest time this could be
            var oldestTime = DateTime.Now.AddMinutes(-(int)maxAge);

            // Note which items are cached
            lock (variant.Cache) {
                var idsFound = new List<Xid>();
                foreach (Xid id in ids) {
                    var record = (ARecordLoader)variant.Cache.Get("asset-" + id.ToString());
                    if (null != record && (record.AsAt >= oldestTime || maxAge == MaxAge.Any)) {
                        output.Add(record);
                    }
                }
            }

            return output;
        }
 internal ResultantNodes(IEnumerable<GenericNode> nodes, MaxAge maxAge)
 {
     NodesInternal = new List<GenericNode>(nodes);
     MaxAge = maxAge;
     AsAt = DateTime.Now;
 }
 internal ResultantAssets(IEnumerable<GenericAsset> assets, MaxAge maxAge)
 {
     AssetsInternal = new List<GenericAsset>(assets);
     MaxAge = maxAge;
     AsAt = DateTime.Now;
 }