/// <summary>
        /// Searches the specified <paramref name="hub">Hub</paramref> for the specified <paramref name="method"/>.
        /// </summary>
        /// <remarks>
        /// In the case that there are multiple overloads of the specified <paramref name="method"/>, the <paramref name="parameter">parameter set</paramref> helps determine exactly which instance of the overload should be resolved. 
        /// If there are multiple overloads found with the same number of matching paramters, none of the methods will be returned because it is not possible to determine which overload of the method was intended to be resolved.
        /// </remarks>
        /// <param name="hub">Hub to search for the specified <paramref name="method"/> on.</param>
        /// <param name="method">The method name to search for.</param>
        /// <param name="descriptor">If successful, the <see cref="MethodDescriptor"/> that was resolved.</param>
        /// <param name="parameters">The set of parameters that will be used to help locate a specific overload of the specified <paramref name="method"/>.</param>
        /// <returns>True if the method matching the name/parameter set is found on the hub, otherwise false.</returns>
        public bool TryGetMethod(HubDescriptor hub, string method, out MethodDescriptor descriptor, params IJsonValue[] parameters)
        {
            string hubMethodKey = BuildHubExecutableMethodCacheKey(hub, method, parameters);

            if (!_executableMethods.TryGetValue(hubMethodKey, out descriptor))
            {
                IEnumerable<MethodDescriptor> overloads;

                if (FetchMethodsFor(hub).TryGetValue(method, out overloads))
                {
                    var matches = overloads.Where(o => o.Matches(parameters)).ToList();

                    // If only one match is found, that is the "executable" version, otherwise none of the methods can be returned because we don't know which one was actually being targeted
                    descriptor = matches.Count == 1 ? matches[0] : null;
                }
                else
                {
                    descriptor = null;
                }

                // If an executable method was found, cache it for future lookups (NOTE: we don't cache null instances because it could be a surface area for DoS attack by supplying random method names to flood the cache)
                if (descriptor != null)
                {
                    _executableMethods.TryAdd(hubMethodKey, descriptor);
                }
            }

            return descriptor != null;
        }
Пример #2
0
        public IHub Create(HubDescriptor descriptor)
        {
            if(descriptor.Type == null)
            {
                return null;
            }

            object hub = _resolver.Resolve(descriptor.Type) ?? Activator.CreateInstance(descriptor.Type);
            return hub as IHub;
        }
 public bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
 {
     switch (Mode)
     {
         case AuthorizeMode.Both:
         case AuthorizeMode.Outgoing:
             return UserAuthorized(request.User);
         default:
             Debug.Assert(Mode == AuthorizeMode.Incoming); // Guard in case new values are added to the enum
             return true;
     }
 }
        public bool TryGetMethod(HubDescriptor hub, string method, out MethodDescriptor descriptor, params JToken[] parameters)
        {
            IEnumerable<MethodDescriptor> overloads;

            if(FetchMethodsFor(hub).TryGetValue(method, out overloads))
            {
                var matches = overloads.Where(o => o.Matches(parameters)).ToList();
                if(matches.Count == 1)
                {
                    descriptor = matches.First();
                    return true;
                }
            }

            descriptor = null;
            return false;
        }
        private static string BuildHubExecutableMethodCacheKey(HubDescriptor hub, string method, IJsonValue[] parameters)
        {
            string normalizedParameterCountKeyPart;

            if (parameters != null)
            {
                normalizedParameterCountKeyPart = parameters.Length.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                // NOTE: we normailize a null parameter array to be the same as an empty (i.e. Length == 0) parameter array
                normalizedParameterCountKeyPart = "0";
            }

            // NOTE: we always normalize to all uppercase since method names are case insensitive and could theoretically come in diff. variations per call
            string normalizedMethodName = method.ToUpperInvariant();

            string methodKey = hub.Name + "::" + normalizedMethodName + "(" + normalizedParameterCountKeyPart + ")";

            return methodKey;
        }
 /// <summary>
 /// Builds a dictionary of all possible methods on a given hub.
 /// Single entry contains a collection of available overloads for a given method name (key).
 /// This dictionary is being cached afterwards.
 /// </summary>
 /// <param name="hub">Hub to build cache for</param>
 /// <returns>Dictionary of available methods</returns>
 private IDictionary<string, IEnumerable<MethodDescriptor>> BuildMethodCacheFor(HubDescriptor hub)
 {
     return ReflectionHelper.GetExportedHubMethods(hub.Type)
         .GroupBy(GetMethodName, StringComparer.OrdinalIgnoreCase)
         .ToDictionary(group => group.Key,
                       group => group.Select(oload =>
                           new MethodDescriptor
                           {
                               ReturnType = oload.ReturnType,
                               Name = group.Key,
                               Invoker = oload.Invoke,
                               Parameters = oload.GetParameters()
                                   .Select(p => new ParameterDescriptor
                                       {
                                           Name = p.Name,
                                           Type = p.ParameterType,
                                       })
                                   .ToList()
                           }),
                       StringComparer.OrdinalIgnoreCase);
 }
 protected virtual bool OnBeforeAuthorizeConnect(HubDescriptor hub, IRequest request)
 {
     return true;
 }
 public bool TryGetHub(string hubName, out HubDescriptor descriptor)
 {
     return _hubs.Value.TryGetValue(hubName, out descriptor);
 }
Пример #9
0
 public IHub Create(HubDescriptor descriptor)
 {
     return (IHub)ObjectFactory.GetInstance(descriptor.Type);
 }
Пример #10
0
 /// <summary>
 /// Builds a dictionary of all possible methods on a given hub.
 /// Single entry contains a collection of available overloads for a given method name (key).
 /// This dictionary is being cached afterwards.
 /// </summary>
 /// <param name="hub">Hub to build cache for</param>
 /// <returns>Dictionary of available methods</returns>
 private IDictionary <string, IEnumerable <MethodDescriptor> > BuildMethodCacheFor(HubDescriptor hub)
 {
     return(ReflectionHelper.GetExportedHubMethods(hub.Type)
            .GroupBy(GetMethodName, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(group => group.Key,
                          group => group.Select(oload =>
                                                new MethodDescriptor
     {
         ReturnType = oload.ReturnType,
         Name = group.Key,
         NameSpecified = (GetMethodAttributeName(oload) != null),
         Invoker = oload.Invoke,
         Hub = hub,
         Attributes = oload.GetCustomAttributes(typeof(Attribute), inherit: true).Cast <Attribute>(),
         Parameters = oload.GetParameters()
                      .Select(p => new ParameterDescriptor
         {
             Name = p.Name,
             Type = p.ParameterType,
         })
                      .ToList()
     }),
                          StringComparer.OrdinalIgnoreCase));
 }
Пример #11
0
 /// <summary>
 /// Retrieves an existing dictionary of all available methods for a given hub from cache.
 /// If cache entry does not exist - it is created automatically by BuildMethodCacheFor.
 /// </summary>
 /// <param name="hub"></param>
 /// <returns></returns>
 private IDictionary <string, IEnumerable <MethodDescriptor> > FetchMethodsFor(HubDescriptor hub)
 {
     return(_methods.GetOrAdd(
                hub.Name,
                key => BuildMethodCacheFor(hub)));
 }
Пример #12
0
 public IEnumerable <MethodDescriptor> GetMethods(HubDescriptor hub)
 {
     return(FetchMethodsFor(hub)
            .SelectMany(kv => kv.Value)
            .ToList());
 }
Пример #13
0
        /// <summary>
        /// Processes the hub's incoming method calls.
        /// </summary>
        protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
        {
            HubRequest hubRequest = _requestParser.Parse(data);

            // Create the hub
            HubDescriptor descriptor = _manager.EnsureHub(hubRequest.Hub);

            IJsonValue[] parameterValues = hubRequest.ParameterValues;

            // Resolve the method
            MethodDescriptor methodDescriptor = _manager.GetHubMethod(descriptor.Name, hubRequest.Method, parameterValues);

            if (methodDescriptor == null)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "'{0}' method could not be resolved.", hubRequest.Method));
            }

            // Resolving the actual state object
            var state = new TrackingDictionary(hubRequest.State);
            var hub   = CreateHub(request, descriptor, connectionId, state, throwIfFailedToCreate: true);

            Task resultTask;

            try
            {
                // Invoke the method
                object result     = methodDescriptor.Invoker.Invoke(hub, _binder.ResolveMethodParameters(methodDescriptor, parameterValues));
                Type   returnType = result != null?result.GetType() : methodDescriptor.ReturnType;

                if (typeof(Task).IsAssignableFrom(returnType))
                {
                    var task = (Task)result;
                    if (!returnType.IsGenericType)
                    {
                        return(task.ContinueWith(t => ProcessResponse(state, null, hubRequest, t.Exception))
                               .FastUnwrap());
                    }
                    else
                    {
                        // Get the <T> in Task<T>
                        Type resultType = returnType.GetGenericArguments().Single();

                        // Get the correct ContinueWith overload
                        var continueWith = TaskAsyncHelper.GetContinueWith(task.GetType());

                        var taskParameter       = Expression.Parameter(continueWith.Type);
                        var processResultMethod = typeof(HubDispatcher).GetMethod("ProcessTaskResult", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(resultType);

                        var body = Expression.Call(Expression.Constant(this),
                                                   processResultMethod,
                                                   Expression.Constant(state),
                                                   Expression.Constant(hubRequest),
                                                   taskParameter);

                        var lambda = Expression.Lambda(body, taskParameter);

                        var call = Expression.Call(Expression.Constant(task, continueWith.Type), continueWith.Method, lambda);
                        Func <Task <Task> > continueWithMethod = Expression.Lambda <Func <Task <Task> > >(call).Compile();
                        return(continueWithMethod.Invoke().FastUnwrap());
                    }
                }
                else
                {
                    resultTask = ProcessResponse(state, result, hubRequest, null);
                }
            }
            catch (TargetInvocationException e)
            {
                resultTask = ProcessResponse(state, null, hubRequest, e);
            }

            return(resultTask.Then(() => base.OnReceivedAsync(request, connectionId, data))
                   .Catch());
        }
Пример #14
0
 public bool TryGetHub(string hubName, out HubDescriptor descriptor)
 {
     return(_hubs.Value.TryGetValue(hubName, out descriptor));
 }
Пример #15
0
 protected virtual string GetHubName(HubDescriptor descriptor)
 {
     return(Json.CamelCase(descriptor.Name));
 }
 public IEnumerable<MethodDescriptor> GetMethods(HubDescriptor hub)
 {
     return FetchMethodsFor(hub)
         .SelectMany(kv => kv.Value)
         .ToList();
 }
Пример #17
0
 public bool AuthorizeConnect(HubDescriptor hubDescriptor, IRequest request)
 {
     return(Pipeline.AuthorizeConnect(hubDescriptor, request));
 }
 /// <summary>
 /// Builds a dictionary of all possible methods on a given hub.
 /// Single entry contains a collection of available overloads for a given method name (key).
 /// This dictionary is being cached afterwards.
 /// </summary>
 /// <param name="hub">Hub to build cache for</param>
 /// <returns>Dictionary of available methods</returns>
 private IDictionary<string, IEnumerable<MethodDescriptor>> BuildMethodCacheFor(HubDescriptor hub)
 {
     return ReflectionHelper.GetExportedHubMethods(hub.Type)
         .GroupBy(GetMethodName, StringComparer.OrdinalIgnoreCase)
         .ToDictionary(group => group.Key,
                       group => group.Select(oload =>
                           new MethodDescriptor
                           {
                               ReturnType = oload.ReturnType,
                               Name = group.Key,
                               NameSpecified = (GetMethodAttributeName(oload) != null),
                               Invoker = oload.Invoke,
                               Hub = hub,
                               Attributes = oload.GetCustomAttributes(typeof(Attribute), inherit: true).Cast<Attribute>(),
                               Parameters = oload.GetParameters()
                                   .Select(p => new ParameterDescriptor
                                       {
                                           Name = p.Name,
                                           Type = p.ParameterType,
                                       })
                                   .ToList()
                           }),
                       StringComparer.OrdinalIgnoreCase);
 }
 /// <summary>
 /// Retrieves an existing dictionary of all available methods for a given hub from cache.
 /// If cache entry does not exist - it is created automatically by BuildMethodCacheFor.
 /// </summary>
 /// <param name="hub"></param>
 /// <returns></returns>
 private IDictionary<string, IEnumerable<MethodDescriptor>> FetchMethodsFor(HubDescriptor hub)
 {
     return _methods.GetOrAdd(
         hub.Name,
         key => BuildMethodCacheFor(hub));
 }
Пример #20
0
 /// <summary>
 /// Builds a dictionary of all possible methods on a given hub.
 /// Single entry contains a collection of available overloads for a given method name (key).
 /// This dictionary is being cached afterwards.
 /// </summary>
 /// <param name="hub">Hub to build cache for</param>
 /// <returns>Dictionary of available methods</returns>
 private IDictionary <string, IEnumerable <MethodDescriptor> > BuildMethodCacheFor(HubDescriptor hub)
 {
     return(ReflectionHelper.GetExportedHubMethods(hub.Type)
            .GroupBy(GetMethodName, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(group => group.Key,
                          group => group.Select(oload =>
                                                new MethodDescriptor
     {
         ReturnType = oload.ReturnType,
         Name = group.Key,
         Invoker = oload.Invoke,
         Parameters = oload.GetParameters()
                      .Select(p => new ParameterDescriptor
         {
             Name = p.Name,
             Type = p.ParameterType,
         })
                      .ToList()
     }),
                          StringComparer.OrdinalIgnoreCase));
 }