Ejemplo n.º 1
0
        public ServiceInvokeResult InvokeMethod(ServiceInfo service, ServiceMethodInfo method, Dictionary <string, string> paramters)
        {
            List <(ParameterInfo Field, string Value)> methodParameters = method.Method.GetParameters().Select(x => (x, paramters.FirstOrDefault(v => v.Key == x.Name).Value)).ToList();
            List <string> errors       = new List <string>();
            List <object> invokeValues = new List <object>();

            object serviceInstance = null;

            try
            {
                serviceInstance = new HttpContextHelper().HttpContext.RequestServices.GetService(service.ServiceType);
            }
            catch (Exception ex)
            {
                errors.Add($"Cannot instantiate the service. Error: {ex.GetAllMessages()}");
                return(new ServiceInvokeResult {
                    Errors = errors
                });
            }


            foreach (var param in methodParameters)
            {
                try
                {
                    invokeValues.Add(Binder.ConvertToType(param.Value, param.Field.ParameterType));
                }
                catch (Exception ex)
                {
                    errors.Add($"Cannot set entity property {param.Field.Name} to {param.Value}. Error: {ex.GetAllMessages()}");
                }
            }
            if (errors.Count > 0)
            {
                return new ServiceInvokeResult {
                           Errors = errors
                }
            }
            ;


            object result = null;

            try
            {
                result = method.Method.Invoke(serviceInstance, invokeValues.ToArray());

                if (result is Task)
                {
                    ((Task)result).Wait();
                }
            }
            catch (Exception ex)
            {
                errors.Add($"Method invocation resulted with the error: {ex.GetAllDetails()}");
                return(new ServiceInvokeResult {
                    Errors = errors
                });
            }


            try
            {
                if (result == null)
                {
                    return new ServiceInvokeResult {
                               Result = "null"
                    }
                }
                ;
                return(new ServiceInvokeResult {
                    Result = result.ToJson()
                });
            }
            catch (Exception ex)
            {
                return(new ServiceInvokeResult {
                    Result = ex.GetAllDetails()
                }
                       );
            }
        }