예제 #1
0
        /// <summary>
        /// Registers a handler for the given resource pattern that belongs to a worker group.
        ///
        /// A pattern may contain placeholders that acts as wildcards, and will be
        /// parsed and stored in the request.PathParams dictionary.
        /// A placeholder is a resource name part starting with a dollar ($) character:
        ///     s.AddHandler("user.$id", handler) // Will match "user.10", "user.foo", etc.
        /// An anonymous placeholder is a resource name part using an asterisk (*) character:
        ///     s.AddHandler("user.*", handler)   // Will match "user.10", "user.foo", etc.
        /// A full wildcard can be used as last part using a greather than (>) character:
        ///     s.AddHandler("data.>", handler)   // Will match "data.foo", "data.foo.bar", etc.
        ///
        /// If the pattern is already registered, or if there are conflicts among
        /// the handlers, an exception will be thrown.
        ///
        /// All resources of the same group will be handled in order on a single worker task.
        /// The group may contain tags, ${tagName}, where the tag name matches a parameter
        /// placeholder name in the resource pattern.
        /// </summary>
        /// <param name="subpattern">Resource subpattern.</param>
        /// <param name="group">Group pattern. Null or empty means using the resource name as group.</param>
        /// <param name="handler">Resource handler.</param>
        public void AddHandler(string subpattern, string group, IAsyncHandler handler)
        {
            handler = handler ?? throw new ArgumentNullException("handler must not be null.");

            Tuple <Node, List <PathParam> > tuple = fetch(subpattern, null);

            if (tuple.Item1.Handler != null)
            {
                throw new ArgumentException("Registration already done for pattern: " + MergePattern(Pattern, subpattern));
            }
            Node n = tuple.Item1;

            n.Group = new Group(group, subpattern);
            n.SetAndValidateParams(tuple.Item2);
            n.Handler = handler;

            registerEventHandlers(handler);

            ResService serv = registeredService();

            if (serv != null)
            {
                handler.OnRegister(serv, MergePattern(FullPattern, subpattern));
            }
        }
예제 #2
0
 /// <summary>
 /// Registers a handler for the given resource pattern.
 ///
 /// A pattern may contain placeholders that acts as wildcards, and will be
 /// parsed and stored in the request.PathParams dictionary.
 /// A placeholder is a resource name part starting with a dollar ($) character:
 ///     s.AddHandler("user.$id", handler) // Will match "user.10", "user.foo", etc.
 /// An anonymous placeholder is a resource name part using an asterisk (*) character:
 ///     s.AddHandler("user.*", handler)   // Will match "user.10", "user.foo", etc.
 /// A full wildcard can be used as last part using a greather than (>) character:
 ///     s.AddHandler("data.>", handler)   // Will match "data.foo", "data.foo.bar", etc.
 ///
 /// If the pattern is already registered, or if there are conflicts among
 /// the handlers, an exception will be thrown.
 ///
 /// If a <see cref="ResourceGroupAttribute"/> is defined, the method will register
 /// the handler to that group.
 /// </summary>
 /// <remarks>The resource uses its own pattern as group pattern.</remarks>
 /// <param name="subpattern">Resource pattern.</param>
 /// <param name="handler">Resource handler.</param>
 public void AddHandler(string subpattern, IAsyncHandler handler)
 {
     AddHandler(
         subpattern,
         GetHandlerAttribute <ResourceGroupAttribute>(handler)?.Group,
         handler);
 }
예제 #3
0
 public Request(
     ResService service,
     Msg msg,
     string rtype,
     string rname,
     string method,
     IAsyncHandler handler,
     EventHandler eventHandler,
     Dictionary <string, string> pathParams,
     string group,
     string cid,
     JToken rawParams,
     JToken rawToken,
     Dictionary <string, string[]> header,
     string host,
     string remoteAddr,
     string uri,
     string query)
     : base(service, rname, handler, eventHandler, pathParams, query, group)
 {
     this.msg   = msg;
     Type       = RequestTypeHelper.FromString(rtype);
     Method     = method;
     CID        = cid;
     Params     = rawParams == null || rawParams.Type == JTokenType.Null ? null : rawParams;
     Token      = rawToken == null || rawToken.Type == JTokenType.Null ? null : rawToken;
     Header     = header;
     Host       = host;
     RemoteAddr = remoteAddr;
     URI        = uri;
 }
예제 #4
0
 internal Match(IAsyncHandler handler, EventHandler eventHandler, Dictionary <string, string> pathParams, string group)
 {
     Handler      = handler;
     EventHandler = eventHandler;
     Params       = pathParams;
     Group        = group;
 }
예제 #5
0
 /// <summary>
 /// Registers a handler.
 /// If a <see cref="ResourcePatternAttribute"/> is defined, the method will register
 /// the handler on that subpattern, otherwise it will be set as root handler.
 /// If a <see cref="ResourceGroupAttribute"/> is defined, the method will register
 /// the handler to that group.
 /// </summary>
 /// <remarks>The resource uses its own pattern as group pattern.</remarks>
 /// <param name="handler">Resource handler.</param>
 public void AddHandler(IAsyncHandler handler)
 {
     AddHandler(
         GetHandlerAttribute <ResourcePatternAttribute>(handler)?.Pattern,
         GetHandlerAttribute <ResourceGroupAttribute>(handler)?.Group,
         handler);
 }
예제 #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileAppenderLogger"/> class.
        /// </summary>
        /// <param name="fileName">File name to append log entries to.</param>
        /// <param name="asyncHandler">Asynchronous handler for logs processing.</param>
        /// <param name="serializerSource">The serializer source.</param>
        public FileAppenderLogger(
            string fileName,
            IAsyncHandler asyncHandler,
            IJsonSerializerSource serializerSource = null)
        {
            // ReSharper disable JoinNullCheckWithUsage
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

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

            string directoryName = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            // ReSharper restore JoinNullCheckWithUsage
            _fileName        = fileName;
            AsyncHandler     = asyncHandler;
            SerializerSource = serializerSource ?? StdJsonLogging.DefaultSerializerSource;
            if (SerializerSource.Settings.Formatting != Formatting.None)
            {
                throw new NotSupportedException("Serialized json strings should be formatted in a one line.");
            }
        }
 public EmailConfirmationHandler(
     UserManager <CustomIdentityUser> userManager,
     EmailSenderService emailSenderService)
 {
     _userManager = userManager;
     _emailSender = emailSenderService;
 }
예제 #8
0
 /// <summary>
 /// Create new server
 /// </summary>
 /// <param name="serializer">Serializer to use to serialize messages</param>
 /// <param name="asyncHandler">Handler to handle messages from client</param>
 public AsyncServer(ISerializer serializer, IAsyncHandler asyncHandler)
 {
     this.serializer   = serializer;
     this.asyncHandler = asyncHandler;
     Engine            = new AsyncServerEngine(serializer, asyncHandler);
     disposed          = false;
 }
        public static IAsyncHandler <TNewInput, TOutput> Converting <TInput, TOutput, TNewInput>(
            this IInputAsyncConverter <TInput, TOutput, TNewInput> converter,
            IAsyncHandler <TInput, TOutput> handler)
        {
            converter = converter ?? throw new ArgumentNullException(nameof(converter));
            handler   = handler ?? throw new ArgumentNullException(nameof(handler));

            return(new InputConvertedAsyncHandler <TInput, TOutput, TNewInput>(converter, handler));
        }
예제 #10
0
        public static IAsyncHandler <TInput, TOutput> Intercepting <TInput, TOutput>(
            this IAsyncInterceptor <TInput, TOutput> interceptor,
            IAsyncHandler <TInput, TOutput> handler)
        {
            interceptor = interceptor ?? throw new ArgumentNullException(nameof(interceptor));
            handler     = handler ?? throw new ArgumentNullException(nameof(handler));

            return(new InterceptedAsyncHandler <TInput, TOutput>(interceptor, handler));
        }
예제 #11
0
        public void AddHandler <TIn, TOut>(IAsyncHandler <TIn, TOut> asyncHandler)
        {
            if (GetHandler <TIn, TOut>() != null)
            {
                throw new ArgumentException("Уже добавлен");
            }

            handlers.Add(asyncHandler);
        }
예제 #12
0
        public async Task <ActionResult <ConfirmInfoDto> > Index(
            [WorkFlow(typeof(TestWorkflow))]
            IAsyncHandler <CreateNewUserInputDto, ActionResult <ConfirmInfoDto> > handler,
            CreateNewUserInputDto dto)
        {
            var s  = (double)12 / 0;
            var ct = CancellationToken.None;

            return(await handler.Handle(dto, ct));
        }
예제 #13
0
        public async Task <IActionResult> PrimaryAuthentication(
            [FromBody] CustomIdentityUserDto userAuthenticationInfo,
            [FromServices] IAsyncHandler <CustomIdentityUserWithRolesDto, ConfirmationCodeDto> primarySignupHandler)
        {
            await primarySignupHandler.Handle(
                new CustomIdentityUserWithRolesDto(userAuthenticationInfo.UserName, userAuthenticationInfo.UserEmail,
                                                   userAuthenticationInfo.Password), CancellationToken.None);

            return(Ok());
        }
예제 #14
0
 /// <summary>
 /// Initializes a new instance of the ResourceContext class.
 /// </summary>
 /// <param name="service">Service to which the resource context belong.</param>
 /// <param name="resourceName">Resource name without the query part.</param>
 /// <param name="handler">Resource handler.</param>
 /// <param name="pathParams">Path parameters derived from the resource name.</param>
 /// <param name="query">Query part of the resource name.</param>
 public ResourceContext(ResService service, string resourceName, IAsyncHandler handler, EventHandler eventHandler, IDictionary <string, string> pathParams, string query, string group)
 {
     Service           = service;
     ResourceName      = resourceName;
     Handler           = handler;
     this.eventHandler = eventHandler;
     PathParams        = pathParams;
     Query             = query == null ? "" : query;
     Group             = group;
     Items             = new Hashtable();
 }
예제 #15
0
 private static TAttribute GetHandlerAttribute <TAttribute>(IAsyncHandler h) where TAttribute : Attribute
 {
     if (h != null)
     {
         var attr = h.GetType().GetTypeInfo().GetCustomAttribute <TAttribute>();
         if (attr is TAttribute)
         {
             return(attr);
         }
     }
     return(null);
 }
예제 #16
0
 private void registerEventHandlers(IAsyncHandler h)
 {
     MethodInfo[] methods = h.GetType().GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     foreach (MethodInfo method in methods)
     {
         var attrs = method.GetCustomAttributes <EventListenerAttribute>();
         foreach (var attr in attrs)
         {
             AddEventListener(attr.Pattern, (EventHandler)method.CreateDelegate(typeof(EventHandler), h));
         }
     }
 }
예제 #17
0
        /// <summary>
        /// Handles messages of a given query type asynchronously.
        /// </summary>
        /// <typeparam name="TQuery">A query type.</typeparam>
        /// <param name="handler">An asynchronous handler.</param>
        /// <param name="channel">A channel.</param>
        /// <param name="topic">A topic.</param>
        /// <returns>A subscription.</returns>
        public static IDisposable HandleQueryAsync <TQuery>(this IBox box, IAsyncHandler <TQuery> handler, string channel = null, string topic = null) where TQuery : IQuery
        {
            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

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

            return(box.AddAsyncHandler(handler, channel, topic));
        }
예제 #18
0
        /// <summary>
        /// Handles messages of a given query type asynchronously.
        /// </summary>
        /// <typeparam name="TQuery">A query type.</typeparam>
        /// <param name="topic">A topic.</param>
        /// <param name="handler">An asynchronous handler.</param>
        /// <returns>A subscription.</returns>
        public static IDisposable HandleQueryAsync <TQuery>(this ITopic topic, IAsyncHandler <TQuery> handler) where TQuery : IQuery
        {
            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

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

            return(topic.SubscribeWhen((env) => handler.HandleAsync((TQuery)env.Data), (env) => env.Data is TQuery));
        }
예제 #19
0
        /// <summary>
        /// Handles messages of a given command type asynchronously.
        /// </summary>
        /// <typeparam name="TCommand">A command type.</typeparam>
        /// <param name="topic">A topic.</param>
        /// <param name="handler">An asynchronous handler.</param>
        /// <returns>A subscription.</returns>
        public static IDisposable HandleCommandAsync <TCommand>(this ITopic topic, IAsyncHandler <TCommand> handler) where TCommand : ICommand
        {
            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

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

            return(topic.SubscribeWhen((env) => handler.HandleAsync((TCommand)env.Data), (env) => env.Data is TCommand));
        }
예제 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NUnitJsonLogger"/> class.
        /// </summary>
        /// <param name="asyncHandler">Asynchronous log write handler.</param>
        /// <param name="serializerSource">The serializer source.</param>
        public NUnitJsonLogger(
            IAsyncHandler asyncHandler,
            IJsonSerializerSource serializerSource = null)
        {
            if (asyncHandler == null)
            {
                throw new ArgumentNullException(nameof(asyncHandler));
            }

            AsyncHandler = asyncHandler;

            SerializerSource = serializerSource ?? StdJsonLogging.DefaultSerializerSource;

            _localZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
        }
예제 #21
0
        /// <summary>
        /// Adds an asynchronous event handler.
        /// </summary>
        /// <typeparam name="T">The message type.</typeparam>
        /// <param name="box">A Postal.NET implementation.</param>
        /// <param name="handler">The handler.</param>
        /// <param name="channel">An optional channel.</param>
        /// <param name="topic">An optional topic.</param>
        /// <returns>A subscription.</returns>
        public static IDisposable AddAsyncHandler <T>(this IBox box, IAsyncHandler <T> handler, string channel = null, string topic = null)
        {
            if (channel == string.Empty)
            {
                channel = null;
            }

            if (topic == string.Empty)
            {
                topic = null;
            }

            return(box
                   .Channel(channel ?? Postal.All)
                   .Topic(topic ?? Postal.All)
                   .SubscribeWhen(async(env) => await handler.HandleAsync((T)env.Data), env => env.Data is T));
        }
예제 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConsoleJsonLogger"/> class.
        /// </summary>
        /// <param name="asyncHandler">Asynchronous log write handler.</param>
        /// <param name="serializerSource">Logging serializer. Used to convert objects to strings and to JObject.</param>
        /// <param name="maxSeverity">Maximal visible severity.</param>
        public ConsoleJsonLogger(
            IAsyncHandler asyncHandler,
            IJsonSerializerSource serializerSource = null,
            LogSeverity maxSeverity = LogSeverity.Debug)
        {
            _maxSeverity = maxSeverity;
            if (asyncHandler == null)
            {
                throw new ArgumentNullException(nameof(asyncHandler));
            }

            AsyncHandler = asyncHandler;

            SerializerSource = serializerSource ?? StdJsonLogging.DefaultSerializerSource;

            _localZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
        }
예제 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextJsonLogger"/> class.
        /// </summary>
        /// <param name="asyncHandler">Asynchronous log write handler.</param>
        /// <param name="writeAction">Action that performs entry write operation.</param>
        /// <param name="serializerSource">The serializer source.</param>
        public TextJsonLogger(
            IAsyncHandler asyncHandler,
            Action <string> writeAction,
            IJsonSerializerSource serializerSource = null)
        {
            if (asyncHandler == null)
            {
                throw new ArgumentNullException(nameof(asyncHandler));
            }

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

            _writeAction     = writeAction;
            AsyncHandler     = asyncHandler;
            SerializerSource = serializerSource
                               ?? new JsonSerializerSource(
                () => StdJsonLogging.DefaultSerializerSource.CreateSettings());

            _localZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
        }
예제 #24
0
 public async Task <ActionResult <ConfirmInfoDto> > Index(
     [WorkFlow(typeof(TestWorkflow))] IAsyncHandler <CreateNewUserInputDto, ActionResult <ConfirmInfoDto> > handler,
     CreateNewUserInputDto dto) => await handler.Handle(dto, CancellationToken.None);
 public AsyncServerEngineSafe(ISerializer serializer, IAsyncHandler asyncHandler, TaskCompletionSource <object> source)
     : base(serializer, asyncHandler) =>
     this.source = source;
예제 #26
0
 public IAsyncHandler <TIn> Create <TIn>(IAsyncHandler <TIn> asyncRollBackHandler)
 => new VoidAsyncHandlerWrapper <TIn>(asyncRollBackHandler);
예제 #27
0
 /// <summary>
 /// Create new server
 /// </summary>
 /// <param name="serializer">Serializer to use to serialize messages</param>
 /// <param name="asyncHandler">Handler to handle messages from client</param>
 public AsyncServer(ISerializer serializer, IAsyncHandler asyncHandler)
 {            
     m_actor = NetMQActor.Create(new AsyncServerEngine(serializer, asyncHandler));
 }
예제 #28
0
        /// <summary>
        /// Create new server with default serializer
        /// </summary>
        /// <param name="asyncHandler">Handler to handle messages from client</param>
        public AsyncServer(IAsyncHandler asyncHandler) : this(Global.DefaultSerializer, asyncHandler)
        {

        }
 public Task <TOutput> ConvertAsync(IAsyncHandler <TInput, TOutput> handler, TNewInput input)
 => handler.HandleAsync(input);
예제 #30
0
 public Task <TNewOutput> ConvertAsync(IAsyncHandler <TInput, TOutput> handler, TInput input)
 => handler.HandleAsync(input).ContinueWith(t => (TNewOutput)t.Result);
 public IAsyncHandler <TIn, TOut> Create <TIn, TOut>(IAsyncHandler <TIn, TOut> handler) =>
 new ResultAsyncHandlerWrapper <TIn, TOut>(handler);
예제 #32
0
 /// <summary>
 /// Create new server
 /// </summary>
 /// <param name="serializer">Serializer to use to serialize messages</param>
 /// <param name="asyncHandler">Handler to handle messages from client</param>
 public AsyncServer(ISerializer serializer, IAsyncHandler asyncHandler)
 {
     m_actor = NetMQActor.Create(new AsyncServerEngine(serializer, asyncHandler));
 }