public virtual JsonRpcResponse Execute()
        {
            JsonRpcResponse response = new JsonRpcResponse();
            // get the method from RpcMethods
            MethodInfo mi = RpcMethods.FirstOrDefault(m => m.Name.Equals(Method, StringComparison.InvariantCultureIgnoreCase));

            // if its not there get it from all methods
            if (mi == null)
            {
                mi = AllMethods.FirstOrDefault(m => m.Name.Equals(Method, StringComparison.InvariantCultureIgnoreCase));
            }
            // if its not there set error in the response
            if (mi == null)
            {
                response = GetErrorResponse(JsonRpcFaultCodes.MethodNotFound);
            }
            else
            {
                ExecutionRequest execRequest = ExecutionRequest.Create(Incubator, mi, GetInputParameters(mi));
                if (execRequest.Execute())
                {
                    response.Result = execRequest.Result;
                }
                else
                {
                    response = GetErrorResponse(JsonRpcFaultCodes.InternalError);
                }
            }

            return(response);
        }
 /// <summary>
 /// The method executed server side
 /// </summary>
 /// <param name="request"></param>
 public virtual void ExecuteRemoteAsync(AsyncExecutionRequest request) // this should be executing server side after encryption has been handled
 {
     Task.Run(() =>
     {
         AsyncCallbackService asyncCallback = _proxyFactory.GetProxy <AsyncCallbackService>(request.RespondToHostName, request.RespondToPort, Logger);
         // This executes server side after the SecureChannel has decrypted and validated, need to set IsInitialized to true to
         // ensure the request doesn't reinitialize to a state where it believes it is an execution request
         // targeting SecureChannel since that is what is in the HttpContext.Request.Url
         ExecutionRequest execRequest = new ExecutionRequest
         {
             ClassName       = request.ClassName,
             MethodName      = request.MethodName,
             Ext             = "json",
             ServiceProvider = ServiceProvider,
             JsonParams      = request.JsonParams,
             IsInitialized   = true,
             Context         = HttpContext
         };
         bool success = execRequest.Execute();
         AsyncExecutionResponse response = new AsyncExecutionResponse
         {
             Success = success,
             Request = request,
             Result  = execRequest.Result
         };
         asyncCallback.RecieveAsyncExecutionResponse(response);
     });
 }
 /// <summary>
 /// The method executed server side
 /// </summary>
 /// <param name="request"></param>
 public virtual void ExecuteRemoteAsync(AsyncExecutionRequest request) // this should be executing server side after encryption has been handled
 {
     Task.Run(() =>
     {
         AsyncCallbackService asyncCallback = _proxyFactory.GetProxy <AsyncCallbackService>(request.RespondToHostName, request.RespondToPort);
         ExecutionRequest execRequest       = new ExecutionRequest(request.ClassName, request.MethodName, "json")
         {
             ServiceProvider = ServiceProvider,
             Context         = HttpContext,
             JsonParams      = request.JsonParams
         };
         bool success = execRequest.Execute();
         AsyncExecutionResponse response = new AsyncExecutionResponse
         {
             Success = success,
             Request = request,
             Result  = execRequest.Result
         };
         if (!success)
         {
             if (execRequest?.Result is ValidationResult validation && validation.Success == false)
             {
                 response.ValidationFailure = new ValidationFailure {
                     Message = validation.Message, Failures = validation.ValidationFailures
                 };
                 response.Result = null;
             }
         }
         asyncCallback.RecieveAsyncExecutionResponse(response);
     });
 }
Esempio n. 4
0
        public void ShouldBeAbleToSwitchOutServiceProviderAndReExecute()
        {
            ExecutionRequest request = CreateExecutionRequest("/SwitchTest/Do.json");
            Incubator        bad     = new Incubator();

            request.ServiceProvider = bad;

            Expect.IsFalse(request.Execute());

            Incubator good = new Incubator();

            good.Set <SwitchTest>(new SwitchTest());
            request.ServiceProvider = good;

            Expect.IsTrue(request.Execute());
            Expect.AreEqual("Yay it worked", request.Result);
        }
Esempio n. 5
0
        public void ShouldSetContext()
        {
            ExecutionRequest execRequest = CreateExecutionRequest("/TakesContextTest/Monkey.json");

            ServiceProxySystem.Register <TakesContextTest>();
            Expect.IsFalse(_setContextCalled.Value);
            execRequest.Execute();
            Expect.IsTrue(_setContextCalled.Value);
        }
        public override bool TryRespond(IHttpContext context)
        {
            try
            {
                RequestWrapper  request  = context.Request as RequestWrapper;
                ResponseWrapper response = context.Response as ResponseWrapper;
                string          appName  = ApplicationNameResolver.ResolveApplicationName(context);

                bool responded = false;

                if (request != null && response != null)
                {
                    string path = request.Url.AbsolutePath.ToLowerInvariant();

                    if (path.StartsWith("/{0}"._Format(ResponderSignificantName.ToLowerInvariant())))
                    {
                        if (path.StartsWith(MethodFormPrefixFormat._Format(ResponderSignificantName).ToLowerInvariant()))
                        {
                            responded = SendMethodForm(context);
                        }
                        else
                        {
                            responded = SendProxyCode(context);
                        }
                    }
                    else
                    {
                        ExecutionRequest execRequest = ResolveExecutionRequest(context, appName);
                        responded = execRequest.Execute();
                        if (responded)
                        {
                            // TODO: make this configurable
                            response.AddHeader("Access-Control-Allow-Origin", "*");
                            response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
                            response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
                            // ---
                            RenderResult(appName, path, execRequest);
                        }
                    }
                }
                if (responded)
                {
                    OnResponded(context);
                }
                else
                {
                    OnNotResponded(context);
                }
                return(responded);
            }
            catch (Exception ex)
            {
                Logger.AddEntry("An error occurred in {0}.{1}: {2}", ex, this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                OnNotResponded(context);
                return(false);
            }
        }
Esempio n. 7
0
        public void ExecutionRequestShouldExecuteWithParameters()
        {
            string           url         = "/TestExecutor/DoExecuteWithParameters.json?input=bananas";
            ExecutionRequest execRequest = CreateExecutionRequest(url);
            TestExecutor     execTarget  = new TestExecutor();

            execRequest.ServiceProvider.Set(typeof(TestExecutor), execTarget);
            Expect.IsTrue(execRequest.Execute());
            Expect.AreEqual("bananas", execRequest.Result);
        }
        public void ExecuteShouldSucceed()
        {
            ServiceProxySystem.Register <TestClass>();
            ExecutionRequest er     = new ExecutionRequest("TestClass", "ShouldWork", "json");
            ValidationResult result = er.Validate();

            Expect.IsTrue(result.Success);
            er.Execute();
            Expect.IsTrue(er.Result.Equals("Yay"));
            Message.PrintLine(er.Result.ToString());
        }
Esempio n. 9
0
        public void ExecutionRequestShouldExecute()
        {
            string           url         = "http://blah.com/TestExecutor/DoExecute.json";
            RequestWrapper   req         = new RequestWrapper(new { Headers = new NameValueCollection(), Url = new Uri(url), HttpMethod = "GET", ContentLength = 0, QueryString = new NameValueCollection() });
            ResponseWrapper  res         = new ResponseWrapper(new object());
            ExecutionRequest execRequest = new ExecutionRequest(req, res);
            TestExecutor     execTarget  = new TestExecutor();

            execRequest.ServiceProvider.Set(typeof(TestExecutor), execTarget);
            Expect.IsTrue(execRequest.Execute());
            Expect.AreEqual(execTarget.Value, execRequest.Result);
        }
Esempio n. 10
0
        public override bool TryRespond(IHttpContext context)
        {
            try
            {
                RequestWrapper  request  = context.Request as RequestWrapper;
                ResponseWrapper response = context.Response as ResponseWrapper;
                string          appName  = AppConf.AppNameFromUri(request.Url, BamConf.AppConfigs);

                bool responded = false;

                if (request != null && response != null)
                {
                    string path = request.Url.AbsolutePath.ToLowerInvariant();

                    if (path.StartsWith("/{0}"._Format(ResponderSignificantName.ToLowerInvariant())))
                    {
                        if (path.StartsWith(MethodFormPrefixFormat._Format(ResponderSignificantName).ToLowerInvariant()))
                        {
                            responded = SendMethodForm(context, appName);
                        }
                        else
                        {
                            responded = SendProxyCode(request, response, path);
                        }
                    }
                    else
                    {
                        ExecutionRequest execRequest = CreateExecutionRequest(context, appName);
                        responded = execRequest.Execute();
                        if (responded)
                        {
                            RenderResult(appName, path, execRequest);
                        }
                    }
                }
                if (responded)
                {
                    OnResponded(context);
                }
                else
                {
                    OnNotResponded(context);
                }
                return(responded);
            }
            catch (Exception ex)
            {
                Logger.AddEntry("An error occurred in {0}.{1}: {2}", ex, this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message);
                OnNotResponded(context);
                return(false);
            }
        }
Esempio n. 11
0
        public ScriptRenderer(ExecutionRequest request, ContentResponder content)
            : base(request, content, "application/javascript", Extensions)
        {
            this._cache    = new ConcurrentDictionary <string, byte[]>();
            this._minCache = new ConcurrentDictionary <string, byte[]>();
            string path = request.Request.Url.AbsolutePath;

            if (!request.WasExecuted)
            {
                request.Execute();
            }

            if (request.Success && request.Result is AppMetaResult)
            {
                request.Result = ((AppMetaResult)request.Result).Data;
            }

            HandlePrependAndPostpend();

            string script = request.Result as string;

            if (script == null)
            {
                string type = "null";

                if (request.Result != null)
                {
                    type           = request.Result.GetType().Name;
                    request.Result = script;
                }

                script = ";\r\nalert('expected a script but was ({0}) instead');"._Format(type);
            }
            Task.Run(() => content.SetScriptCache(path, script));
            SetResult();
        }