Пример #1
0
 public LightNodeOptions(AcceptVerbs defaultAcceptVerb, IContentFormatter defaultFormatter, params IContentFormatter[] specifiedFormatters)
 {
     DefaultAcceptVerb = defaultAcceptVerb;
     DefaultFormatter = defaultFormatter;
     SpecifiedFormatters = specifiedFormatters;
     UseOtherMiddleware = false;
 }
Пример #2
0
 public ExposureKeySetBuilderV1(IExposureKeySetHeaderInfoConfig headerInfoConfig, IExposureKeySetSigning exposureKeySetSigning, IUtcDateTimeProvider dateTimeProvider, IContentFormatter contentFormatter)
 {
     _ExposureKeySetSigning = exposureKeySetSigning;
     _DateTimeProvider      = dateTimeProvider;
     _ContentFormatter      = contentFormatter;
     _Config = headerInfoConfig;
 }
 public ReturnStatusCodeException(HttpStatusCode statusCode, string reasonPhrase = null, object content = null, IContentFormatter contentFormatter = null)
 {
     this.StatusCode = statusCode;
     this.ReasonPhrase = reasonPhrase;
     this.content = content;
     this.contentFormatter = contentFormatter;
 }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IRandomStringProvider randomStringProvider = dependencyResolver.Resolve <IRandomStringProvider>();

            IContentFormatter contentFormatter = dependencyResolver.Resolve <IContentFormatter>();

            if (_baseRedirectUri == null)
            {
                IAppEnvironmentProvider appEnvironmentProvider = dependencyResolver
                                                                 .Resolve <IAppEnvironmentProvider>();

                AppEnvironment activEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

                _baseRedirectUri = $"{activEnvironment.Security.SSOServerUrl}/connect/authorize?scope={string.Join(" ", activEnvironment.Security.Scopes)}&client_id={activEnvironment.Security.ClientName}&redirect_uri={activEnvironment.GetConfig("ClientHostBaseUri", context.Request.Host.Value)}{activEnvironment.GetConfig("ClientHostVirtualPath", "/")}SignIn&response_type=id_token token";
            }

            string nonce = randomStringProvider.GetRandomNonSecureString(12);

            string stateArgs = string.Join(string.Empty, context.Request.Path.Value.SkipWhile(c => c == '/'));

            string redirectUrl = $"{_baseRedirectUri}&state={stateArgs}&nonce={nonce}";

            context.Response.Redirect(redirectUrl);
        }
Пример #5
0
 /// <summary>
 /// 设置指定业务对应的内容模板
 /// </summary>
 /// <param name="bizFlag">业务标志</param>
 /// <param name="formatter">内容模板</param>
 public void SetFormatter(string bizFlag, IContentFormatter formatter)
 {
     if (!string.IsNullOrWhiteSpace(bizFlag) && formatter != null)
     {
         this._dic.AddOrUpdate(bizFlag, formatter, (k, v) => formatter);
     }
 }
Пример #6
0
 public ReturnStatusCodeException(HttpStatusCode statusCode, object content = null, IContentFormatter contentFormatter = null, Action<HttpContext> contextEmitter = null)
 {
     this.StatusCode = (int)statusCode;
     this.content = content;
     this.contentFormatter = contentFormatter;
     this.contextEmitter = contextEmitter;
 }
 public ReturnStatusCodeException(HttpStatusCode statusCode, string reasonPhrase = null, object content = null, IContentFormatter contentFormatter = null)
 {
     this.StatusCode       = statusCode;
     this.ReasonPhrase     = reasonPhrase;
     this.content          = content;
     this.contentFormatter = contentFormatter;
 }
Пример #8
0
 public ReturnStatusCodeException(HttpStatusCode statusCode, object content = null, IContentFormatter contentFormatter = null, Action <HttpContext> contextEmitter = null)
 {
     this.StatusCode       = (int)statusCode;
     this.content          = content;
     this.contentFormatter = contentFormatter;
     this.contextEmitter   = contextEmitter;
 }
Пример #9
0
 public Property(string label, object value, IContentFormatter formatter = null, bool isMultiLine = false)
 {
     Label       = label;
     Value       = value;
     IsMultiLine = isMultiLine;
     _formatter  = formatter ?? new DefaultContentFormatter();
 }
Пример #10
0
 public ReturnStatusCodeException(HttpStatusCode statusCode, string reasonPhrase = null, object content = null, IContentFormatter contentFormatter = null, Action<IDictionary<string, object>> environmentEmitter = null)
 {
     this.StatusCode = (int)statusCode;
     this.ReasonPhrase = reasonPhrase;
     this.content = content;
     this.contentFormatter = contentFormatter;
     this.environmentEmitter = environmentEmitter;
 }
Пример #11
0
 public ReturnStatusCodeException(HttpStatusCode statusCode, string reasonPhrase = null, object content = null, IContentFormatter contentFormatter = null, Action <IDictionary <string, object> > environmentEmitter = null)
 {
     this.StatusCode         = statusCode;
     this.ReasonPhrase       = reasonPhrase;
     this.content            = content;
     this.contentFormatter   = contentFormatter;
     this.environmentEmitter = environmentEmitter;
 }
        public static IAppBuilder UseIMOwin(this IAppBuilder app, BehaviorRouter behaviorRouter, IMOwinFilterCollection filters, IContentFormatter contentFormatter, ErrorHandlingPolicy errorHandlingPolicy)
        {
            var option = new IMOwinOptions(behaviorRouter, contentFormatter, filters)
            {
                ErrorHandlingPolicy = errorHandlingPolicy,
            };

            return UseIMOwin(app, option);
        }
Пример #13
0
 internal OperationInfo(OperationHandler handler)
 {
     this.ClassName         = handler.ClassName;
     this.MethodName        = handler.MethodName;
     this.AcceptVerbs       = handler.AcceptVerb;
     this.Parameters        = handler.Arguments;
     this.ReturnType        = handler.ReturnType;
     this.ForceUseFormatter = handler.ForceUseFormatter;
 }
Пример #14
0
 public IMOwinOptions(BehaviorRouter router, IContentFormatter contentFormatter, IMOwinFilterCollection filters)
 {
     this.BehaviorRouter = router;
     this.ContentFormatter = contentFormatter;
     this.UseOtherMiddleware = false;
     this.ErrorHandlingPolicy = ErrorHandlingPolicy.ThrowException;
     this.Filters = new IMOwinFilterCollection();
     this.StreamWriteOption = StreamWriteOption.BufferAndWrite;
     this.Filters = filters;
 }
Пример #15
0
        public Matrix(
            List <T> cells,
            Expression <Func <T, string> > colExpr,
            Expression <Func <T, string> > rowExpr,
            Func <IEnumerable <T>, string, string, object> cellRenderer,
            IContentFormatter formatter = null
            )
        {
            _contentFormatter = formatter ?? new DefaultContentFormatter();

            this.AddClass("matrix");

            var cols = cells.AsQueryable().GroupBy(colExpr).Select(e => e.Key).Distinct().ToList();
            var rows = cells.AsQueryable().GroupBy(rowExpr).Select(e => e.Key).Distinct().ToList();

            this.Styles["grid-template-columns"] = $"auto repeat({cols.Count}, 1fr);";

            var colFunc = colExpr.Compile();
            var rowFunc = rowExpr.Compile();

            Div MakeColHeader(object label)
            {
                var div = new Div(new Span(label.ToString()));

                div.SetClass("col-header");
                return(div);
            }

            Div MakeRowHeader(object label)
            {
                var div = new Div(new Span(label.ToString()));

                div.SetClass("row-header");
                return(div);
            }

            Div MakeCell(object content)
            {
                var div = new Div(_contentFormatter.Format(content));

                div.SetClass("cell");
                return(div);
            }

            this.VisualTree.AddRange(cols.Select(MakeColHeader).ToArray().Prepend(new Div(new Literal(""))));

            foreach (var row in rows)
            {
                this.VisualTree.AddRange(
                    cols.Select(col => cellRenderer(
                                    cells.Where(e => colFunc(e).Equals(col) && rowFunc(e).Equals(row)), col, row)).Select(MakeCell).ToArray()
                    .Prepend(MakeRowHeader(row))
                    );
            }
        }
 /// <summary>Append operation specific option.</summary>
 /// <param name="contentFormatterFactory">Ignore default formatter and specifiedFormatters. Force use this contentFormatter.</param>
 public OperationOptionAttribute(Type contentFormatterFactory)
 {
     try
     {
         this.ContentFormatter = (Activator.CreateInstance(contentFormatterFactory) as IContentFormatterFactory).CreateFormatter();
     }
     catch (Exception ex)
     {
         throw new ArgumentException("contentFormatterFactory must inherits IContentFormatterFactory and has parameterless constructor", ex);
     }
 }
Пример #17
0
 public LightNodeOptions(AcceptVerbs defaultAcceptVerb, IContentFormatter defaultFormatter, params IContentFormatter[] specifiedFormatters)
 {
     DefaultAcceptVerb = defaultAcceptVerb;
     DefaultFormatter = defaultFormatter;
     SpecifiedFormatters = specifiedFormatters;
     UseOtherMiddleware = false;
     ParameterStringImplicitNullAsDefault = false;
     ParameterEnumAllowsFieldNameParse = false;
     StreamWriteOption = Server.StreamWriteOption.BufferAndWrite;
     ErrorHandlingPolicy = Server.ErrorHandlingPolicy.ThrowException;
     Filters = new LightNodeFilterCollection();
 }
Пример #18
0
 public LightNodeOptions(AcceptVerbs defaultAcceptVerb, IContentFormatter defaultFormatter, params IContentFormatter[] specifiedFormatters)
 {
     DefaultAcceptVerb   = defaultAcceptVerb;
     DefaultFormatter    = defaultFormatter;
     SpecifiedFormatters = specifiedFormatters;
     UseOtherMiddleware  = false;
     ParameterStringImplicitNullAsDefault = false;
     ParameterEnumAllowsFieldNameParse    = false;
     StreamWriteOption   = Server.StreamWriteOption.BufferAndWrite;
     ErrorHandlingPolicy = Server.ErrorHandlingPolicy.ThrowException;
     Filters             = new LightNodeFilterCollection();
 }
Пример #19
0
        public override async Task Invoke(IOwinContext context)
        {
            IContentFormatter contentFormatter =
                context.GetDependencyResolver().Resolve <IContentFormatter>();

            IAppMetadataProvider appMetadataProvider =
                context.GetDependencyResolver().Resolve <IAppMetadataProvider>();

            context.Response.ContentType = "application/json; charset=utf-8";

            await context.Response.WriteAsync(contentFormatter.Serialize(await appMetadataProvider.GetAppMetadata()), context.Request.CallCancelled);
        }
 public ExposureKeySetBuilderV1(
     IExposureKeySetHeaderInfoConfig headerInfoConfig,
     IContentSigner gaenContentSigner,
     IContentSigner nlContentSigner,
     IUtcDateTimeProvider dateTimeProvider,
     IContentFormatter contentFormatter)
 {
     _GaenContentSigner = gaenContentSigner;
     _NlContentSigner   = nlContentSigner;
     _DateTimeProvider  = dateTimeProvider;
     _ContentFormatter  = contentFormatter;
     _Config            = headerInfoConfig;
 }
Пример #21
0
        public WindowsEventsLogStore(IContentFormatter contentFormatter, IAppEnvironmentProvider appEnvironmentProvider)
        {
            if (contentFormatter == null)
            {
                throw new ArgumentNullException(nameof(contentFormatter));
            }

            if (appEnvironmentProvider == null)
            {
                throw new ArgumentNullException(nameof(appEnvironmentProvider));
            }

            _contentFormatter     = contentFormatter;
            _activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();
        }
Пример #22
0
        public DefaultAppEnvironmentProvider(IPathProvider pathProvider, IContentFormatter contentFormatter)
        {
            if (pathProvider == null)
            {
                throw new ArgumentNullException(nameof(pathProvider));
            }

            if (contentFormatter == null)
            {
                throw new ArgumentNullException(nameof(contentFormatter));
            }

            _pathProvider     = pathProvider;
            _contentFormatter = contentFormatter;
        }
Пример #23
0
 public LightNodeOptions(AcceptVerbs defaultAcceptVerb, IContentFormatter defaultFormatter, params IContentFormatter[] specifiedFormatters)
 {
     DefaultAcceptVerb   = defaultAcceptVerb;
     DefaultFormatter    = defaultFormatter;
     SpecifiedFormatters = specifiedFormatters;
     UseOtherMiddleware  = false;
     ParameterStringImplicitNullAsDefault = false;
     ParameterEnumAllowsFieldNameParse    = false;
     StreamWriteOption              = Server.StreamWriteOption.BufferAndWrite;
     ErrorHandlingPolicy            = Server.ErrorHandlingPolicy.ThrowException;
     OperationMissingHandlingPolicy = Server.OperationMissingHandlingPolicy.ReturnErrorStatusCode;
     Filters = new LightNodeFilterCollection();
     OperationCoordinatorFactory = new DefaultOperationCoordinatorFactory();
     ServerEngineId = Guid.NewGuid().ToString();
     Logger         = NullLightNodeLogger.Instance;
 }
Пример #24
0
        public static HttpContent ToContent(this object instance, IContentFormatter formatter)
        {
            var stream = new MemoryStream();

            try
            {
                formatter.WriteToStream(instance, stream);
                stream.Position = 0;
                return(new StreamContent(stream));
            }
            catch
            {
                stream.Dispose();
                throw;
            }
        }
        public DefaultSSOPageModelProvider(IContentFormatter contentFormatter, IAppEnvironmentProvider appEnvironmentProvider)
        {
            if (appEnvironmentProvider == null)
            {
                throw new ArgumentNullException(nameof(appEnvironmentProvider));
            }

            if (contentFormatter == null)
            {
                throw new ArgumentNullException(nameof(contentFormatter));
            }

            _activeAppEnvironment = appEnvironmentProvider.GetActiveAppEnvironment();

            _contentFormatter = contentFormatter;
        }
Пример #26
0
 public LightNodeOptions(AcceptVerbs defaultAcceptVerb, IContentFormatter defaultFormatter, params IContentFormatter[] specifiedFormatters)
 {
     DefaultAcceptVerb = defaultAcceptVerb;
     DefaultFormatter = defaultFormatter;
     SpecifiedFormatters = specifiedFormatters;
     UseOtherMiddleware = false;
     ParameterStringImplicitNullAsDefault = false;
     ParameterEnumAllowsFieldNameParse = false;
     StreamWriteOption = Server.StreamWriteOption.BufferAndWrite;
     ErrorHandlingPolicy = Server.ErrorHandlingPolicy.ThrowException;
     OperationMissingHandlingPolicy = Server.OperationMissingHandlingPolicy.ReturnErrorStatusCode;
     Filters = new LightNodeFilterCollection();
     OperationCoordinatorFactory = new DefaultOperationCoordinatorFactory();
     ServerEngineId = Guid.NewGuid().ToString();
     Logger = NullLightNodeLogger.Instance; 
 }
Пример #27
0
        public DefaultPageModelProvider(IContentFormatter contentFormatter, IAppEnvironmentProvider appEnvironmentProvider, IUserSettingProvider usersSettingsProvider = null)
        {
            if (appEnvironmentProvider == null)
            {
                throw new ArgumentNullException(nameof(appEnvironmentProvider));
            }

            if (contentFormatter == null)
            {
                throw new ArgumentNullException(nameof(contentFormatter));
            }

            _usersSettingsProvider  = usersSettingsProvider;
            _appEnvironmentProvider = appEnvironmentProvider;
            _contentFormatter       = contentFormatter;
        }
Пример #28
0
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IContentFormatter contentFormatter =
                context.RequestServices.GetService <IContentFormatter>();

            IAppMetadataProvider appMetadataProvider =
                context.RequestServices.GetService <IAppMetadataProvider>();

            context.Response.ContentType = "application/json; charset=utf-8";

            await context.Response.WriteAsync(contentFormatter.Serialize(await appMetadataProvider.GetAppMetadata().ConfigureAwait(false)), context.RequestAborted).ConfigureAwait(false);
        }
Пример #29
0
        public override async Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IContentFormatter contentFormatter =
                context.GetDependencyResolver().Resolve <IContentFormatter>();

            IAppMetadataProvider appMetadataProvider =
                context.GetDependencyResolver().Resolve <IAppMetadataProvider>();

            context.Response.ContentType = "application/json; charset=utf-8";

            await context.Response.WriteAsync(contentFormatter.Serialize(await appMetadataProvider.GetAppMetadata().ConfigureAwait(false)), context.Request.CallCancelled).ConfigureAwait(false);
        }
Пример #30
0
        internal void EmitCode(ILightNodeOptions options, IDictionary <string, object> environment)
        {
            environment[OwinConstants.ResponseStatusCode] = (int)StatusCode;
            if (ReasonPhrase != null)
            {
                environment[OwinConstants.ResponseReasonPhrase] = ReasonPhrase;
            }
            if (content != null)
            {
                contentFormatter = contentFormatter ?? options.DefaultFormatter;
                var encoding       = contentFormatter.Encoding;
                var responseHeader = environment.AsResponseHeaders();
                responseHeader["Content-Type"] = new[] { contentFormatter.MediaType + ((encoding == null) ? "" : "; charset=" + encoding.WebName) };

                if (environmentEmitter != null)
                {
                    environmentEmitter(environment);
                }

                var responseStream = environment.AsResponseBody();
                if (options.StreamWriteOption == StreamWriteOption.DirectWrite)
                {
                    contentFormatter.Serialize(new UnclosableStream(responseStream), content);
                }
                else
                {
                    using (var buffer = new MemoryStream())
                    {
                        contentFormatter.Serialize(new UnclosableStream(buffer), content);
                        responseHeader["Content-Length"] = new[] { buffer.Position.ToString() };
                        buffer.Position = 0;
                        if (options.StreamWriteOption == StreamWriteOption.BufferAndWrite)
                        {
                            buffer.CopyTo(responseStream); // not CopyToAsync
                        }
                        else
                        {
                            // EmitCode is void:)
                            buffer.CopyTo(responseStream);
                        }
                    }
                }
            }
        }
Пример #31
0
        internal void EmitCode(ILightNodeOptions options, IDictionary<string, object> environment)
        {
            environment[OwinConstants.ResponseStatusCode] = (int)StatusCode;
            if (ReasonPhrase != null)
            {
                environment[OwinConstants.ResponseReasonPhrase] = ReasonPhrase;
            }
            if (content != null)
            {
                contentFormatter = contentFormatter ?? options.DefaultFormatter;
                var encoding = contentFormatter.Encoding;
                var responseHeader = environment.AsResponseHeaders();
                responseHeader["Content-Type"] = new[] { contentFormatter.MediaType + ((encoding == null) ? "" : "; charset=" + encoding.WebName) };

                if (environmentEmitter != null)
                {
                    environmentEmitter(environment);
                }

                var responseStream = environment.AsResponseBody();
                if (options.StreamWriteOption == StreamWriteOption.DirectWrite)
                {
                    contentFormatter.Serialize(new UnclosableStream(responseStream), content);
                }
                else
                {
                    using (var buffer = new MemoryStream())
                    {
                        contentFormatter.Serialize(new UnclosableStream(buffer), content);
                        responseHeader["Content-Length"] = new[] { buffer.Position.ToString() };
                        buffer.Position = 0;
                        if (options.StreamWriteOption == StreamWriteOption.BufferAndWrite)
                        {
                            buffer.CopyTo(responseStream); // not CopyToAsync
                        }
                        else
                        {
                            // EmitCode is void:)
                            buffer.CopyTo(responseStream);
                        }
                    }
                }
            }
        }
        internal void EmitCode(IIMOwinOptions options, IDictionary<string, object> environment)
        {
            environment[OwinConstants.ResponseStatusCode] = (int)StatusCode;
            if (ReasonPhrase != null)
            {
                environment[OwinConstants.ResponseReasonPhrase] = ReasonPhrase;
            }
            if (Content != null)
            {
                _contentFormatter = _contentFormatter ?? options.ContentFormatter;
                var encoding = _contentFormatter.Encoding;
                var responseHeader = environment.AsResponseHeaders();
                responseHeader["Content-Type"] = new[] { _contentFormatter.MediaType + ((encoding == null) ? "" : "; charset=" + encoding.WebName) };

                var responseStream = environment.AsResponseBody();
                if (options.StreamWriteOption == StreamWriteOption.DirectWrite)
                {
                    _contentFormatter.Serialize(new UnclosableStream(responseStream), Content);
                }
                else
                {
                    using (var buffer = new MemoryStream())
                    {
                        _contentFormatter.Serialize(new UnclosableStream(buffer), Content);
                        responseHeader["Content-Length"] = new[] { buffer.Position.ToString(CultureInfo.InvariantCulture) };
                        buffer.Position = 0;
                        if (options.StreamWriteOption == StreamWriteOption.BufferAndWrite)
                        {
                            buffer.CopyTo(responseStream); // not CopyToAsync
                        }
                        else
                        {
                            // can't await in catch clouse..
                            // return buffer.CopyToAsync(responseStream);
                            buffer.CopyTo(responseStream);
                        }
                    }
                }
            }
        }
Пример #33
0
        internal void EmitCode(ILightNodeOptions options, HttpContext httpContext)
        {
            httpContext.Response.StatusCode = (int)StatusCode;
   
            if (content != null)
            {
                contentFormatter = contentFormatter ?? options.DefaultFormatter;
                var encoding = contentFormatter.Encoding;
                var responseHeader = httpContext.Response.Headers;
                responseHeader["Content-Type"] = new[] { contentFormatter.MediaType + ((encoding == null) ? "" : "; charset=" + encoding.WebName) };

                contextEmitter?.Invoke(httpContext);

                var responseStream = httpContext.Response.Body;
                if (options.StreamWriteOption == StreamWriteOption.DirectWrite)
                {
                    contentFormatter.Serialize(new UnclosableStream(responseStream), content);
                }
                else
                {
                    using (var buffer = new MemoryStream())
                    {
                        contentFormatter.Serialize(new UnclosableStream(buffer), content);
                        responseHeader["Content-Length"] = new[] { buffer.Position.ToString() };
                        buffer.Position = 0;
                        if (options.StreamWriteOption == StreamWriteOption.BufferAndWrite)
                        {
                            buffer.CopyTo(responseStream); // not CopyToAsync
                        }
                        else
                        {
                            // EmitCode is void:)
                            buffer.CopyTo(responseStream);
                        }
                    }
                }
            }
        }
Пример #34
0
        internal void EmitCode(ILightNodeOptions options, HttpContext httpContext)
        {
            httpContext.Response.StatusCode = (int)StatusCode;

            if (content != null)
            {
                contentFormatter = contentFormatter ?? options.DefaultFormatter;
                var encoding       = contentFormatter.Encoding;
                var responseHeader = httpContext.Response.Headers;
                responseHeader["Content-Type"] = new[] { contentFormatter.MediaType + ((encoding == null) ? "" : "; charset=" + encoding.WebName) };

                contextEmitter?.Invoke(httpContext);

                var responseStream = httpContext.Response.Body;
                if (options.StreamWriteOption == StreamWriteOption.DirectWrite)
                {
                    contentFormatter.Serialize(new UnclosableStream(responseStream), content);
                }
                else
                {
                    using (var buffer = new MemoryStream())
                    {
                        contentFormatter.Serialize(new UnclosableStream(buffer), content);
                        responseHeader["Content-Length"] = new[] { buffer.Position.ToString() };
                        buffer.Position = 0;
                        if (options.StreamWriteOption == StreamWriteOption.BufferAndWrite)
                        {
                            buffer.CopyTo(responseStream); // not CopyToAsync
                        }
                        else
                        {
                            // EmitCode is void:)
                            buffer.CopyTo(responseStream);
                        }
                    }
                }
            }
        }
Пример #35
0
        public OperationHandler(ILightNodeOptions options, Type classType, MethodInfo methodInfo)
        {
            this.ClassName  = classType.Name;
            this.MethodName = methodInfo.Name;
            this.Arguments  = methodInfo.GetParameters()
                              .Select(x => new ParameterInfoSlim(x))
                              .ToArray();
            this.ParameterNames = Arguments.Select(x => x.Name).ToList().AsReadOnly();
            this.ReturnType     = methodInfo.ReturnType;

            this.filters = options.Filters
                           .Concat(classType.GetCustomAttributes <LightNodeFilterAttribute>(true))
                           .Concat(methodInfo.GetCustomAttributes <LightNodeFilterAttribute>(true))
                           .OrderBy(x => x.Order)
                           .ToArray();

            var operationOption = methodInfo.GetCustomAttributes <OperationOptionAttribute>(true).FirstOrDefault()
                                  ?? classType.GetCustomAttributes <OperationOptionAttribute>(true).FirstOrDefault();

            this.AcceptVerb = (operationOption != null && operationOption.AcceptVerbs != null)
                ? operationOption.AcceptVerbs.Value
                : options.DefaultAcceptVerb;

            var verbSpecifiedAttr = methodInfo.GetCustomAttributes <HttpVerbAttribtue>(true);

            if (verbSpecifiedAttr.Any())
            {
                this.AcceptVerb = verbSpecifiedAttr.Aggregate((AcceptVerbs)0, (x, y) => x | y.AcceptVerbs);
            }

            this.ForceUseFormatter = (operationOption != null && operationOption.ContentFormatter != null)
                ? operationOption.ContentFormatter
                : null;
            var formatterChoiceBase = new[] { options.DefaultFormatter }.Concat(options.SpecifiedFormatters).Where(x => x != null).ToArray();

            this.optionFormatters           = formatterChoiceBase;
            this.formatterByExt             = formatterChoiceBase.SelectMany(x => (x.Ext ?? "").Split('|'), (fmt, ext) => new { fmt, ext }).ToLookup(x => x.ext, x => x.fmt, StringComparer.OrdinalIgnoreCase);
            this.formatterByMediaType       = formatterChoiceBase.ToLookup(x => x.MediaType, StringComparer.OrdinalIgnoreCase);
            this.formatterByContentEncoding = formatterChoiceBase.ToLookup(x => x.ContentEncoding, StringComparer.OrdinalIgnoreCase);

            this.AttributeLookup = classType.GetCustomAttributes(true)
                                   .Concat(methodInfo.GetCustomAttributes(true))
                                   .Cast <Attribute>()
                                   .ToLookup(x => x.GetType());

            foreach (var argument in this.Arguments)
            {
                if (!TypeBinder.IsAllowType(argument.ParameterType))
                {
                    throw new InvalidOperationException(string.Format("parameter is not allowed, class:{0} method:{1} paramName:{2} paramType:{3}",
                                                                      classType.Name, methodInfo.Name, argument.Name, argument.ParameterType.FullName));
                }
            }

            // prepare lambda parameters
            var envArg     = Expression.Parameter(typeof(IDictionary <string, object>), "environment");
            var envBind = Expression.Bind(typeof(LightNodeContract).GetProperty("Environment"), envArg);
            var args       = Expression.Parameter(typeof(object[]), "args");
            var parameters = methodInfo.GetParameters()
                             .Select((x, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), x.ParameterType))
                             .ToArray();

            // Task or Task<T>
            if (typeof(Task).IsAssignableFrom(this.ReturnType))
            {
                // (object[] args) => new X().M((T1)args[0], (T2)args[1])...
                var lambda = Expression.Lambda <Func <IDictionary <string, object>, object[], Task> >(
                    Expression.Call(
                        Expression.MemberInit(Expression.New(classType), envBind),
                        methodInfo,
                        parameters),
                    envArg, args);

                if (this.ReturnType.IsGenericType && this.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    this.handlerBodyType     = HandlerBodyType.AsyncFunc;
                    this.methodAsyncFuncBody = lambda.Compile();

                    lock (taskResultExtractors)
                    {
                        if (!taskResultExtractors.ContainsKey(this.ReturnType))
                        {
                            // (object task) => (object)((Task<>).Result)
                            var taskParameter = Expression.Parameter(typeof(object), "task");
                            var resultLambda  = Expression.Lambda <Func <object, object> >(
                                Expression.Convert(
                                    Expression.Property(
                                        Expression.Convert(taskParameter, this.ReturnType),
                                        "Result"),
                                    typeof(object)),
                                taskParameter);

                            var compiledResultLambda = resultLambda.Compile();

                            taskResultExtractors[this.ReturnType] = compiledResultLambda;
                        }
                    }
                }
                else
                {
                    this.handlerBodyType       = HandlerBodyType.AsyncAction;
                    this.methodAsyncActionBody = lambda.Compile();
                }
            }
            else if (this.ReturnType == typeof(void)) // of course void
            {
                // (object[] args) => { new X().M((T1)args[0], (T2)args[1])... }
                var lambda = Expression.Lambda <Action <IDictionary <string, object>, object[]> >(
                    Expression.Call(
                        Expression.MemberInit(Expression.New(classType), envBind),
                        methodInfo,
                        parameters),
                    envArg, args);

                this.handlerBodyType  = HandlerBodyType.Action;
                this.methodActionBody = lambda.Compile();
            }
            else // return T
            {
                // (object[] args) => (object)new X().M((T1)args[0], (T2)args[1])...
                var lambda = Expression.Lambda <Func <IDictionary <string, object>, object[], object> >(
                    Expression.Convert(
                        Expression.Call(
                            Expression.MemberInit(Expression.New(classType), envBind),
                            methodInfo,
                            parameters)
                        , typeof(object)),
                    envArg, args);

                this.handlerBodyType = HandlerBodyType.Func;
                this.methodFuncBody  = lambda.Compile();
            }
        }
 public static IAppBuilder UseIMOwin(this IAppBuilder app, BehaviorRouter behaviorRouter,
     IMOwinFilterCollection filters, IContentFormatter contentFormatter)
 {
     return UseIMOwin(app, behaviorRouter, filters, contentFormatter, ErrorHandlingPolicy.ParseReturnStatusCodeException);
 }
Пример #37
0
 public StreamItemMapper(IContentFormatter contentFormatter)
 {
     this.contentFormatter = contentFormatter;
 }
 public CellRendererFactory(IContentFormatter formatter)
 {
     _formatter = formatter;
 }
Пример #39
0
 /// <summary>
 /// 通过短信发送验证码
 /// </summary>
 /// <param name="formatter">验证码内容模板</param>
 /// <param name="setting">邮箱配置</param>
 /// <param name="subjectFunc">根据业务标志返回对应的邮件主题</param>
 public EMailSender(IContentFormatter formatter, EMailSetting setting, Func <string, string> subjectFunc)
 {
     this.Formatter   = formatter ?? throw new ArgumentNullException(nameof(formatter));
     this.SubjectFunc = subjectFunc ?? throw new ArgumentNullException(nameof(subjectFunc));
     this.EMailHelper = new EMailHelper(setting ?? throw new ArgumentNullException(nameof(setting)));
 }
Пример #40
0
 internal OperationInfo(OperationHandler handler)
 {
     this.ClassName = handler.ClassName;
     this.MethodName = handler.MethodName;
     this.AcceptVerbs = handler.AcceptVerb;
     this.Parameters = handler.Arguments;
     this.ReturnType = handler.ReturnType;
     this.ForceUseFormatter = handler.ForceUseFormatter;
 }
 public ICellRenderer <T> Default(IContentFormatter formatter = null)
 {
     return(new DefaultCell <T>(formatter ?? _formatter));
 }
Пример #42
0
        internal virtual IEnumerable <AxisLabelModel> GenerateLabels()
        {
            AxisPlotMode plotMode       = this.ActualPlotMode;
            int          labelIndex     = 0;
            int          startIndex     = this.LabelOffset;
            int          labelStep      = this.LabelInterval;
            int          skipLabelCount = 1;

            IContentFormatter labelFormatter = this.ContentFormatter;
            object            owner          = this.Presenter;
            string            format         = this.GetLabelFormat();

            // generate label for each major tick
            foreach (AxisTickModel tick in this.ticks)
            {
                if (labelIndex < startIndex)
                {
                    labelIndex++;
                    continue;
                }

                // skip minor ticks
                if (tick.Type == TickType.Minor)
                {
                    continue;
                }

                if (skipLabelCount > 1)
                {
                    skipLabelCount--;
                    continue;
                }

                // no need to process last tick if we are plotting between ticks
                if (plotMode == AxisPlotMode.BetweenTicks && RadMath.IsOne(this.IsInverse ? 1 - tick.normalizedValue : tick.normalizedValue))
                {
                    break;
                }

                AxisLabelModel label   = new AxisLabelModel();
                object         content = this.GetLabelContent(tick);
                if (labelFormatter != null)
                {
                    content = labelFormatter.Format(owner, content);
                }
                else if (!string.IsNullOrEmpty(format))
                {
                    content = string.Format(CultureInfo.CurrentUICulture, format, content);
                }
                label.Content        = content;
                tick.associatedLabel = label;

                if (plotMode == AxisPlotMode.BetweenTicks)
                {
                    decimal length = tick.NormalizedForwardLength;
                    if (length == 0)
                    {
                        length = tick.NormalizedBackwardLength;
                    }
                    tick.associatedLabel.normalizedPosition = tick.normalizedValue + (length / 2);
                }
                else
                {
                    tick.associatedLabel.normalizedPosition = tick.normalizedValue;
                }

                yield return(label);

                skipLabelCount = labelStep;
            }
        }
Пример #43
0
 // default no filters
 public IMOwinOptions(BehaviorRouter router, IContentFormatter contentFormatter) : this(router, contentFormatter, new IMOwinFilterCollection()) { }
Пример #44
0
        public OperationHandler(ILightNodeOptions options, Type classType, MethodInfo methodInfo)
        {
            this.ClassName = classType.Name;
            this.MethodName = methodInfo.Name;
            this.Arguments = methodInfo.GetParameters()
                .Select(x => new ParameterInfoSlim(x))
                .ToArray();
            this.ParameterNames = Arguments.Select(x => x.Name).ToList().AsReadOnly();
            this.ReturnType = methodInfo.ReturnType;

            this.filters = options.Filters
                .Concat(classType.GetCustomAttributes<LightNodeFilterAttribute>(true))
                .Concat(methodInfo.GetCustomAttributes<LightNodeFilterAttribute>(true))
                .OrderBy(x => x.Order)
                .ToArray();

            var operationOption = methodInfo.GetCustomAttributes<OperationOptionAttribute>(true).FirstOrDefault()
                               ?? classType.GetCustomAttributes<OperationOptionAttribute>(true).FirstOrDefault();
            this.AcceptVerb = (operationOption != null && operationOption.AcceptVerbs != null)
                ? operationOption.AcceptVerbs.Value
                : options.DefaultAcceptVerb;

            var verbSpecifiedAttr = methodInfo.GetCustomAttributes<HttpVerbAttribtue>(true);
            if (verbSpecifiedAttr.Any())
            {
                this.AcceptVerb = verbSpecifiedAttr.Aggregate((AcceptVerbs)0, (x, y) => x | y.AcceptVerbs);
            }

            this.ForceUseFormatter = (operationOption != null && operationOption.ContentFormatter != null)
                ? operationOption.ContentFormatter
                : null;
            var formatterChoiceBase = new[] { options.DefaultFormatter }.Concat(options.SpecifiedFormatters).Where(x => x != null).ToArray();
            this.optionFormatters = formatterChoiceBase;
            this.formatterByExt = formatterChoiceBase.SelectMany(x => (x.Ext ?? "").Split('|'), (fmt, ext) => new { fmt, ext }).ToLookup(x => x.ext, x => x.fmt, StringComparer.OrdinalIgnoreCase);
            this.formatterByMediaType = formatterChoiceBase.ToLookup(x => x.MediaType, StringComparer.OrdinalIgnoreCase);
            this.formatterByContentEncoding = formatterChoiceBase.ToLookup(x => x.ContentEncoding, StringComparer.OrdinalIgnoreCase);

            this.AttributeLookup = classType.GetCustomAttributes(true)
                .Concat(methodInfo.GetCustomAttributes(true))
                .Cast<Attribute>()
                .ToLookup(x => x.GetType());

            foreach (var argument in this.Arguments)
            {
                if (!TypeBinder.IsAllowType(argument.ParameterType))
                {
                    throw new InvalidOperationException(string.Format("parameter is not allowed, class:{0} method:{1} paramName:{2} paramType:{3}",
                        classType.Name, methodInfo.Name, argument.Name, argument.ParameterType.FullName));
                }
            }

            // prepare lambda parameters
            var envArg = Expression.Parameter(typeof(IDictionary<string, object>), "environment");
            var envBind = Expression.Bind(typeof(LightNodeContract).GetProperty("Environment"), envArg);
            var args = Expression.Parameter(typeof(object[]), "args");
            var parameters = methodInfo.GetParameters()
                .Select((x, i) => Expression.Convert(Expression.ArrayIndex(args, Expression.Constant(i)), x.ParameterType))
                .ToArray();

            // Task or Task<T>
            if (typeof(Task).IsAssignableFrom(this.ReturnType))
            {
                // (object[] args) => new X().M((T1)args[0], (T2)args[1])...
                var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], Task>>(
                    Expression.Call(
                        Expression.MemberInit(Expression.New(classType), envBind),
                        methodInfo,
                        parameters),
                    envArg, args);

                if (this.ReturnType.IsGenericType && this.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
                {
                    this.handlerBodyType = HandlerBodyType.AsyncFunc;
                    this.methodAsyncFuncBody = lambda.Compile();

                    lock (taskResultExtractors)
                    {
                        if (!taskResultExtractors.ContainsKey(this.ReturnType))
                        {
                            // (object task) => (object)((Task<>).Result)
                            var taskParameter = Expression.Parameter(typeof(object), "task");
                            var resultLambda = Expression.Lambda<Func<object, object>>(
                                Expression.Convert(
                                    Expression.Property(
                                        Expression.Convert(taskParameter, this.ReturnType),
                                        "Result"),
                                    typeof(object)),
                                taskParameter);

                            var compiledResultLambda = resultLambda.Compile();

                            taskResultExtractors[this.ReturnType] = compiledResultLambda;
                        }
                    }
                }
                else
                {
                    this.handlerBodyType = HandlerBodyType.AsyncAction;
                    this.methodAsyncActionBody = lambda.Compile();
                }
            }
            else if (this.ReturnType == typeof(void)) // of course void
            {
                // (object[] args) => { new X().M((T1)args[0], (T2)args[1])... }
                var lambda = Expression.Lambda<Action<IDictionary<string, object>, object[]>>(
                    Expression.Call(
                        Expression.MemberInit(Expression.New(classType), envBind),
                        methodInfo,
                        parameters),
                    envArg, args);

                this.handlerBodyType = HandlerBodyType.Action;
                this.methodActionBody = lambda.Compile();
            }
            else // return T
            {
                // (object[] args) => (object)new X().M((T1)args[0], (T2)args[1])...
                var lambda = Expression.Lambda<Func<IDictionary<string, object>, object[], object>>(
                    Expression.Convert(
                        Expression.Call(
                            Expression.MemberInit(Expression.New(classType), envBind),
                            methodInfo,
                            parameters)
                    , typeof(object)),
                    envArg, args);

                this.handlerBodyType = HandlerBodyType.Func;
                this.methodFuncBody = lambda.Compile();
            }
        }
Пример #45
0
 public ConsoleLogStore(IContentFormatter formatter)
 {
     _formatter = formatter;
 }
Пример #46
0
 public DebugLogStore(IContentFormatter formatter)
 {
     _formatter = formatter;
 }