public override void RunJob()
        {
            Logger.DebugFormat("begin restore data for module {0}", _module.ModuleName);
            SetStepsCount(_module.Tables.Count(t => !IgnoredTables.Contains(t.Name)));

            using (var connection = _factory.OpenConnection())
            {
                foreach (var table in _module.GetTablesOrdered().Where(t => !IgnoredTables.Contains(t.Name) && t.InsertMethod != InsertMethod.None))
                {
                    Logger.DebugFormat("begin restore table {0}", table.Name);

                    var transactionsCommited = 0;
                    var rowsInserted         = 0;
                    ActionInvoker.Try(
                        state =>
                        RestoreTable(connection.Fix(), (TableInfo)state, ref transactionsCommited,
                                     ref rowsInserted), table, 5,
                        onAttemptFailure: error => _columnMapper.Rollback(),
                        onFailure: error => { throw ThrowHelper.CantRestoreTable(table.Name, error); });

                    SetStepCompleted();
                    Logger.DebugFormat("{0} rows inserted for table {1}", rowsInserted, table.Name);
                }
            }

            Logger.DebugFormat("end restore data for module {0}", _module.ModuleName);
        }
        protected override void ExecuteCore()
        {
            var queryString = HttpContext.Request.QueryString;

            if (queryString.Keys.Count > 0 && String.Equals(queryString.GetValues(0).First(), "json", StringComparison.OrdinalIgnoreCase))
            {
                ActionInvoker.InvokeAction(ControllerContext, "Internal::Proxy");
                return;
            }

            // This is where the proxy places the action.
            string action = HttpContext.Request.Headers["x-mvc-action"] ?? HttpContext.Request.QueryString["action"];

            if (!RouteData.Values.ContainsKey("action") && !String.IsNullOrEmpty(action))
            {
                RouteData.Values.Add("action", action);
            }

            if (RouteData.Values.ContainsKey("action"))
            {
                base.ExecuteCore();
                return;
            }

            ActionInvoker.InvokeAction(ControllerContext, "Internal::ProxyDefinition");
        }
Example #3
0
        public Tables()
        {
            InitializeComponent();



            for (int i = 0; i <= 100; i += 10)
            {
                var col = new FlexColumn()
                {
                    ColumnName = i.ToString()
                };

                flexGrid.Columns.Add(col);
            }

            for (int i = 500; i <= 9000; i += 250)
            {
                var row = new FlexRow()
                {
                    RowName = i.ToString()
                };

                flexGrid.Rows.Add(row);
            }

            _actionHandler = new ActionInvoker(OnAction);
            MessageBus.Instance.Subscribe(Actions.TABLES_FOCUS_CONTROL, _actionHandler);
            MessageBus.Instance.Subscribe(Actions.SHOW_EDITOR, _actionHandler);
        }
Example #4
0
        public void TestInvoke1()
        {
            var one = ActionInvoker.Create(typeof(Tester).GetMethod("One"));

            one.Invoke(_tester, 0);
            Assert.That(_tester.HasInvoked, Is.True);
        }
Example #5
0
        static void Main(string[] args)
        {
            print();

            ActionInvoker aliasToInvokePrint = print;

            print();
            aliasToInvokePrint();

            aliasToInvokePrint = SayHi;

            aliasToInvokePrint();

            Person p = new Person();

            aliasToInvokePrint = p.Jump;

            aliasToInvokePrint();

            //aliasToInvokePrint = MethodThatReturnsInInt;

            Calculation calc = Subtract;

            int result = calc(3, 4);

            ExecuteAndPrint(calc);

            ExecuteAndPrint(Divide);
            ExecuteAndPrint(Multiply);
            //ExecuteAndPrint(print);
            Console.ReadLine();
        }
Example #6
0
        /// <summary>
        /// The process request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="HttpResponse"/>.
        /// </returns>
        public override HttpResponse ProcessRequest(HttpRequest request)
        {
            if (request.ProtocolVersion.Major < 3)
            {
                HttpResponse response;

                try
                {
                    var controller   = this.CreateController(request);
                    var actionResult = new ActionInvoker().InvokeAction(controller, request.Action);
                    response = actionResult.GetResponse();
                }
                catch (HttpNotFoundException exception)
                {
                    response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotFound, exception.Message);
                }
                catch (Exception exception)
                {
                    response = new HttpResponse(
                        request.ProtocolVersion,
                        HttpStatusCode.InternalServerError,
                        exception.Message);
                }

                return(response);
            }

            return(new HttpResponse(
                       request.ProtocolVersion,
                       HttpStatusCode.NotImplemented,
                       "Request cannot be handled."));
        }
Example #7
0
 protected ControllerBase(ActionInvoker actionInvoker, DataContext dataContext, JsonMapperManager jsonMapperManager, DeviceHiveConfiguration deviceHiveConfiguration) :
     base(actionInvoker)
 {
     _dataContext             = dataContext;
     _jsonMapperManager       = jsonMapperManager;
     _deviceHiveConfiguration = deviceHiveConfiguration;
 }
        public void QueryRetrievesOutputDefinitions()
        {
            var testItem = new TestItem("Baby");
            var server   = new Server("Test", testItem);
            var invoker  = new ActionInvoker(server);
            var result   = invoker.Query(
                "urn:ccnet:test:baby",
                new QueryArguments {
                DataToInclude = DataDefinitions.OutputOnly
            });

            Assert.IsNotNull(result);
            Assert.AreEqual(RemoteResultCode.Success, result.ResultCode);
            var expected = new[]
            {
                new RemoteActionDefinition
                {
                    Name        = "DoSomething",
                    Description = "This will do something",
                    OutputData  = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />"
                },
                new RemoteActionDefinition
                {
                    Name        = "TestAction",
                    Description = "This is a test action",
                    OutputData  = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />"
                }
            };

            CollectionAssert.AreEqual(expected, result.Actions.OrderBy(rad => rad.Name), new DefinitionComparer());
        }
        public void QueryReturnsActions()
        {
            var testItem = new TestItem("Baby");
            var server   = new Server("Test", testItem);
            var invoker  = new ActionInvoker(server);
            var result   = invoker.Query("urn:ccnet:test:baby", null);

            Assert.IsNotNull(result);
            Assert.AreEqual(RemoteResultCode.Success, result.ResultCode);
            var expected = new[]
            {
                new RemoteActionDefinition
                {
                    Name        = "DoSomething",
                    Description = "This will do something",
                    InputData   = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />",
                    OutputData  = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />"
                },
                new RemoteActionDefinition
                {
                    Name        = "TestAction",
                    Description = "This is a test action",
                    InputData   = "<definition name=\"SingleValue\" namespace=\"urn:cruisecontrol:common\">" +
                                  "<value name=\"Value\" type=\"string\" />" +
                                  "</definition>",
                    OutputData = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />"
                }
            };

            CollectionAssert.AreEqual(expected, result.Actions.OrderBy(rad => rad.Name), new DefinitionComparer());
        }
Example #10
0
 public virtual void Execute(HttpRequestContext requestContext)
 {
     if (ActionInvoker != null)
     {
         ActionInvoker.InvokeAction(new ControllerContext(requestContext, this), requestContext.Action);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagementClient"/> class for managing content of the specified project.
        /// </summary>
        /// <param name="ManagementOptions">The settings of the Kentico Kontent project.</param>
        public ManagementClient(ManagementOptions ManagementOptions)
        {
            if (ManagementOptions == null)
            {
                throw new ArgumentNullException(nameof(ManagementOptions));
            }

            if (string.IsNullOrEmpty(ManagementOptions.ProjectId))
            {
                throw new ArgumentException("Kentico Kontent project identifier is not specified.", nameof(ManagementOptions.ProjectId));
            }

            if (!Guid.TryParse(ManagementOptions.ProjectId, out _))
            {
                throw new ArgumentException($"Provided string is not a valid project identifier ({ManagementOptions.ProjectId}). Haven't you accidentally passed the API key instead of the project identifier?", nameof(ManagementOptions.ProjectId));
            }

            if (string.IsNullOrEmpty(ManagementOptions.ApiKey))
            {
                throw new ArgumentException("The API key is not specified.", nameof(ManagementOptions.ApiKey));
            }

            _urlBuilder    = new EndpointUrlBuilder(ManagementOptions);
            _urlBuilderV2  = new EndpointUrlBuilderV2(ManagementOptions);
            _actionInvoker = new ActionInvoker(
                new ManagementHttpClient(new DefaultResiliencePolicyProvider(ManagementOptions.MaxRetryAttempts), ManagementOptions.EnableResilienceLogic),
                new MessageCreator(ManagementOptions.ApiKey));
            _modelProvider = ManagementOptions.ModelProvider ?? new ModelProvider();
        }
Example #12
0
 public void TestThatFiveParametersIsTooMany()
 {
     Assert.That(
         () => ActionInvoker.Create(typeof(TestActionInvoker).GetMethod(nameof(FiveParameters))),
         Throws.TypeOf <NotSupportedException>()
         );
 }
Example #13
0
        public void TestInvoke0()
        {
            var one = ActionInvoker.Create(typeof(Tester).GetMethod(nameof(Tester.Zero)));

            one.Invoke(_tester);
            Assert.That(_tester.HasInvoked, Is.True);
        }
Example #14
0
 public void TestInvokeFunc()
 {
     Assert.That(
         () => ActionInvoker.Create(typeof(TestActionInvoker).GetMethod(nameof(AFunc))),
         Throws.TypeOf <NotSupportedException>()
         );
 }
Example #15
0
        public void TestStaticInvokeThunk()
        {
            var setTrueStaticInvoked = ActionInvoker.Create(typeof(Tester).GetMethod(nameof(Tester.SetInvokedTrue)));

            setTrueStaticInvoked.Invoke();
            Assert.That(Tester.StaticHasInvoked, Is.True);
        }
Example #16
0
        private async Task AssertSecureControllerAccess(ClaimsPrincipal user, string method, int expectedStatusCode, IAuthorizationPolicyStore policyStore = null)
        {
            var ctrl = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.SecureController)).GetControllers(null).Single();

            if (policyStore != null)
            {
                var options = LiteApiOptions.Default;
                foreach (var policy in policyStore.GetPolicyNames())
                {
                    options.AuthorizationPolicyStore.SetPolicy(policy, policyStore.GetPolicy(policy));
                }
                ctrl.Filters = null; // force refresh init with new policy store
                foreach (var action in ctrl.Actions)
                {
                    action.Filters = null;
                }
                ctrl.Init(new LiteApiOptionsAccessor(options));
            }

            var actionCtx = ctrl.Actions.Single(x => string.Compare(method, x.Name, StringComparison.OrdinalIgnoreCase) == 0);
            var invoker   = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(
                                                  new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever()), new JsonSerializer());
            var httpCtx = new Fakes.FakeHttpContext();

            httpCtx.User         = user;
            httpCtx.Request.Path = "/api/secure/" + method;
            await invoker.Invoke(httpCtx, actionCtx);

            Assert.Equal(expectedStatusCode, httpCtx.Response.StatusCode);
        }
Example #17
0
        public void TestInvoke2()
        {
            var one = ActionInvoker.Create(typeof(Tester).GetMethod("Two"));

            one.Invoke(_tester, 0, string.Empty);
            Assert.That(_tester.HasInvoked, Is.True);
        }
Example #18
0
        protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
        {
            var queryString = HttpContext.Request.QueryString;

            if (queryString.Keys.Count > 0 && String.Equals(queryString.GetValues(0).First(), "json", StringComparison.OrdinalIgnoreCase))
            {
                ActionInvoker.InvokeAction(ControllerContext, "Internal::Proxy");
                return(new CompletedAsyncResult()
                {
                    AsyncState = state
                });
            }

            // This is where the proxy places the action.
            string action = HttpContext.Request.Headers["x-mvc-action"] ?? HttpContext.Request.QueryString["action"];

            if (!RouteData.Values.ContainsKey("action") && !String.IsNullOrEmpty(action))
            {
                RouteData.Values.Add("action", action);
            }

            if (RouteData.Values.ContainsKey("action"))
            {
                return(base.BeginExecuteCore(callback, state));
            }
            else
            {
                ActionInvoker.InvokeAction(ControllerContext, "Internal::ProxyDefinition");
                return(new CompletedAsyncResult()
                {
                    AsyncState = state
                });
            }
        }
Example #19
0
        private async Task AssertCall(bool isGet, string path, string query, string body, string expectedResult)
        {
            var ctrlDiscoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RestfulController));
            var ctrls          = ctrlDiscoverer.GetControllers(null);

            var pathResolver = new PathResolver(ctrls);
            var httpCtx      = new Fakes.FakeHttpContext();

            if (isGet)
            {
                (httpCtx.Request as Fakes.FakeHttpRequest).WithPath(path);
            }
            else
            {
                (httpCtx.Request as Fakes.FakeHttpRequest).Method = "POST";
                (httpCtx.Request as Fakes.FakeHttpRequest).WithPath(path);
                (httpCtx.Request as Fakes.FakeHttpRequest).WriteBody(body);
            }
            foreach (var q in query.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = q.Split(":".ToCharArray());
                (httpCtx.Request as Fakes.FakeHttpRequest).AddQuery(parts[0], parts[1]);
            }

            var action        = pathResolver.ResolveAction(httpCtx.Request);
            var actionInvoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer());
            await actionInvoker.Invoke(httpCtx, action);

            string result = httpCtx.Response.ReadBody();

            Assert.Equal(expectedResult, result);
        }
        private void DoDeleteStorage(IEnumerable <string> storageModules, IEnumerable <Tenant> tenants)
        {
            Logger.Debug("begin delete storage");

            foreach (var tenant in tenants)
            {
                foreach (var module in storageModules)
                {
                    var storage = StorageFactory.GetStorage(ConfigPath, tenant.TenantId.ToString(), module);
                    var domains = StorageFactory.GetDomainList(ConfigPath, module).ToList();

                    domains.Add(string.Empty); //instead storage.DeleteFiles("\\", "*.*", true);

                    foreach (var domain in domains)
                    {
                        ActionInvoker.Try(
                            state =>
                        {
                            if (storage.IsDirectory((string)state))
                            {
                                storage.DeleteFiles((string)state, "\\", "*.*", true);
                            }
                        },
                            domain,
                            5,
                            onFailure: error => Logger.WarnFormat("Can't delete files for domain {0}: \r\n{1}", domain, error)
                            );
                    }

                    SetStepCompleted();
                }
            }

            Logger.Debug("end delete storage");
        }
Example #21
0
        public async Task ActionInvokerSerializeEnum_EnumIsSerializedAsString()
        {
            var httpClient    = new FakeManagementHttpClient();
            var actionInvoker = new ActionInvoker(httpClient, new MessageCreator("{api_key}"));

            var assetUpsertModel = new AssetUpsertModel()
            {
                Title        = "Asset",
                Descriptions = new []
                {
                    new AssetDescription()
                    {
                        Description = "Description",
                        Language    = LanguageIdentifier.DEFAULT_LANGUAGE
                    },
                },
                FileReference = new FileReference()
                {
                    Id   = "ab7bdf75-781b-4bf9-aed8-501048860402",
                    Type = FileReferenceTypeEnum.Internal
                }
            };

            await actionInvoker.InvokeMethodAsync <AssetUpsertModel, dynamic>("{endpoint_url}", HttpMethod.Put, assetUpsertModel);

            var expectedRequestBody = "{\"file_reference\":{\"id\":\"ab7bdf75-781b-4bf9-aed8-501048860402\",\"type\":\"internal\"},\"descriptions\":[{\"language\":{\"id\":\"00000000-0000-0000-0000-000000000000\"},\"description\":\"Description\"}],\"title\":\"Asset\"}";

            Assert.Equal(expectedRequestBody, httpClient.requestBody);
        }
 internal ManagementClient(EndpointUrlBuilder urlBuilder, EndpointUrlBuilderV2 urlBuilderV2, ActionInvoker actionInvoker, IModelProvider modelProvider = null)
 {
     _urlBuilder    = urlBuilder ?? throw new ArgumentNullException(nameof(urlBuilder));
     _urlBuilderV2  = urlBuilderV2 ?? throw new ArgumentNullException(nameof(urlBuilderV2));
     _actionInvoker = actionInvoker ?? throw new ArgumentNullException(nameof(actionInvoker));
     _modelProvider = modelProvider ?? new ModelProvider();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentManagementClient"/> class for managing content of the specified project.
        /// </summary>
        /// <param name="contentManagementOptions">The settings of the Kentico Cloud project.</param>
        public ContentManagementClient(ContentManagementOptions contentManagementOptions)
        {
            if (contentManagementOptions == null)
            {
                throw new ArgumentNullException(nameof(contentManagementOptions));
            }

            if (string.IsNullOrEmpty(contentManagementOptions.ProjectId))
            {
                throw new ArgumentException("Kentico Cloud project identifier is not specified.", nameof(contentManagementOptions.ProjectId));
            }

            if (!Guid.TryParse(contentManagementOptions.ProjectId, out Guid projectIdGuid))
            {
                throw new ArgumentException($"Provided string is not a valid project identifier ({contentManagementOptions.ProjectId}). Haven't you accidentally passed the API key instead of the project identifier?", nameof(contentManagementOptions.ProjectId));
            }

            if (string.IsNullOrEmpty(contentManagementOptions.ApiKey))
            {
                throw new ArgumentException("The API key is not specified.", nameof(contentManagementOptions.ApiKey));
            }

            _urlBuilder    = new EndpointUrlBuilder(contentManagementOptions);
            _actionInvoker = new ActionInvoker(new ContentManagementHttpClient(), new MessageCreator(contentManagementOptions.ApiKey));
            _modelProvider = contentManagementOptions.ModelProvider ?? new ModelProvider();
        }
Example #24
0
        public void TestStaticInvoke1()
        {
            var setStaticInvoked = ActionInvoker.Create(typeof(Tester).GetMethod("SetInvoked"));

            setStaticInvoked.Invoke(true);
            Assert.That(Tester.StaticHasInvoked, Is.True);
        }
Example #25
0
        public void ActionInvoker_NullArguments_ThrowException()
        {
            bool error = false;

            try
            {
                var a = new ActionInvoker(null, new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer());
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);

            error = false;
            try
            {
                var a = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), null, new JsonSerializer());
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);
        }
Example #26
0
        private void DoBackupStorage(IDataWriteOperator writer, List <IGrouping <string, BackupFileInfo> > fileGroups)
        {
            Logger.Debug("begin backup storage");

            foreach (var group in fileGroups)
            {
                var filesProcessed = 0;
                var filesCount     = group.Count();

                var storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key);
                foreach (var file in group)
                {
                    ActionInvoker.Try(state =>
                    {
                        var f = (BackupFileInfo)state;
                        using (var fileStream = storage.GetReadStream(f.Domain, f.Path))
                        {
                            var tmp = Path.GetTempFileName();
                            try
                            {
                                using (var tmpFile = File.OpenWrite(tmp))
                                {
                                    fileStream.CopyTo(tmpFile);
                                }

                                writer.WriteEntry(KeyHelper.GetFileZipKey(file), tmp);
                            }
                            finally
                            {
                                if (File.Exists(tmp))
                                {
                                    File.Delete(tmp);
                                }
                            }
                        }
                    }, file, 5, error => Logger.Warn("can't backup file ({0}:{1}): {2}", file.Module, file.Path, error));

                    SetCurrentStepProgress((int)(++filesProcessed * 100 / (double)filesCount));
                }
            }

            var restoreInfoXml = new XElement(
                "storage_restore",
                fileGroups
                .SelectMany(group => group.Select(file => (object)file.ToXElement()))
                .ToArray());

            var tmpPath = Path.GetTempFileName();

            using (var tmpFile = File.OpenWrite(tmpPath))
            {
                restoreInfoXml.WriteTo(tmpFile);
            }

            writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpPath);
            File.Delete(tmpPath);


            Logger.Debug("end backup storage");
        }
Example #27
0
        public async Task Should_not_run_binders_where_instance_does_not_apply()
        {
            var requestGraph   = RequestGraph.CreateFor <IHandler>(x => x.Params(null, null));
            var requestContext = requestGraph.GetRequestContext();

            requestGraph.AddRequestBinder1(c => SetArguments(c, (a, p) => a[0]  = "binder1"));
            requestGraph.AddRequestBinder2(c => SetArguments(c, (a, p) => a[1] += "binder2"),
                                           instanceAppliesTo: x => false);

            var invoker = new ActionInvoker(requestContext, requestGraph.RequestBinders,
                                            requestGraph.ResponseWriters, requestGraph.Configuration);
            var handler = Substitute.For <IHandler>();

            await invoker.Invoke(handler);

            var expectedArguments = new object[] { "binder1", null };

            await requestGraph.ActionMethod.Invoke(handler.Received(1), expectedArguments);

            requestGraph.RequestBinder1.AppliesToCalled.ShouldBeTrue();
            requestGraph.RequestBinder1.AppliesToContext.RequestContext.ShouldEqual(requestContext);
            requestGraph.RequestBinder1.AppliesToContext.ActionArguments.ShouldEqual(expectedArguments);
            requestGraph.RequestBinder1.BindCalled.ShouldBeTrue();
            requestGraph.RequestBinder1.BindContext.RequestContext.ShouldEqual(requestContext);
            requestGraph.RequestBinder1.BindContext.ActionArguments.ShouldEqual(expectedArguments);

            requestGraph.RequestBinder2.AppliesToCalled.ShouldBeTrue();
            requestGraph.RequestBinder2.AppliesToContext.RequestContext.ShouldEqual(requestContext);
            requestGraph.RequestBinder2.AppliesToContext.ActionArguments.ShouldEqual(expectedArguments);
            requestGraph.RequestBinder2.BindCalled.ShouldBeFalse();
        }
        public void GenerateMessageFormatAddsNewNamespace()
        {
            var namespaces = new Dictionary <string, string>();

            ActionInvoker.GenerateMessageFormat(namespaces, typeof(Messages.Blank));
            Assert.IsTrue(namespaces.ContainsKey("CruiseControl.Common.Messages"));
            Assert.AreEqual("urn:cruisecontrol:common", namespaces["CruiseControl.Common.Messages"]);
        }
        public void GenerateMessageFormatHandlesMessageWithoutProperties()
        {
            var namespaces = new Dictionary <string, string>();
            var actual     = ActionInvoker.GenerateMessageFormat(namespaces, typeof(Messages.Blank));
            var expected   = "<definition name=\"Blank\" namespace=\"urn:cruisecontrol:common\" />";

            Assert.AreEqual(expected, actual);
        }
Example #30
0
 public DeviceController(ActionInvoker actionInvoker, DataContext dataContext,
                         JsonMapperManager jsonMapperManager, DeviceHiveConfiguration deviceHiveConfiguration,
                         IMessageManager messageManager, DeviceService deviceService) :
     base(actionInvoker, dataContext, jsonMapperManager, deviceHiveConfiguration)
 {
     _messageManager = messageManager;
     _deviceService  = deviceService;
 }
        public void ProccedAndReturnWithRuntimePolicyOff(ActionInvoker.InvokeActionMethod sut, IAlternateMethodContext context)
        {
            context.Setup(c => c.RuntimePolicyStrategy).Returns(() => RuntimePolicy.Off);

            sut.NewImplementation(context);

            context.Verify(c => c.Proceed());
            context.MessageBroker.Verify(b => b.Publish(It.IsAny<ActionInvoker.InvokeActionMethod.Message>()), Times.Never());
        }
Example #32
0
        private void UpdateAction(ActionInvoker.InvokeActionMethod.Message message, ITabSetupContext context)
        {
            var model = GetModel(context.GetTabStore());

            if (message.IsChildAction)
            {
                model.ChildActionCount++;
            }
            else
            {
                model.ActionName = message.ActionName;
                model.ActionExecutionTime = Math.Round(message.Duration.TotalMilliseconds, 2);
                model.ControllerName = message.ControllerName;
            }
        }
Example #33
0
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            ActionInvoker actionInvoker = new ActionInvoker(this.context, cancellationToken, this.services);

            // Empty filters is the default case so avoid delegates
            // Ensure empty case remains the same as the filtered case
            if (this.filters.Length == 0)
            {
                return actionInvoker.InvokeActionAsync();
            }

            // Ensure delegate continues to use the C# Compiler static delegate caching optimization
            Func<ActionInvoker, Task> invokeCallback = innerInvoker => innerInvoker.InvokeActionAsync();
            return InvokeActionWithActionFilters(this.context, cancellationToken, this.filters, invokeCallback, actionInvoker)();
        }
        public void PublishMessageWithRuntimePolicyOn(ActionInvoker.InvokeActionMethod sut, IAlternateMethodContext context)
        {
            var actionDescriptorMock = new Mock<ActionDescriptor>();
            actionDescriptorMock.Setup(a => a.ControllerDescriptor).Returns(new ReflectedControllerDescriptor(typeof(DummyController)));
            actionDescriptorMock.Setup(a => a.ActionName).Returns("Index");

            context.Setup(c => c.ReturnValue).Returns(new ContentResult());
            context.Setup(c => c.Arguments).Returns(new object[]
                                                            {
                                                                new ControllerContext(),
                                                                actionDescriptorMock.Object,
                                                                new Dictionary<string, object>()
                                                            });

            sut.NewImplementation(context);

            context.TimerStrategy().Verify(t => t.Time(It.IsAny<Action>()));
            context.MessageBroker.Verify(b => b.Publish(It.IsAny<ActionInvoker.InvokeActionMethod.Message>()));
        } 
        public void ActionInvoker_Invokes_GenerateCode_Method_With_Right_ActionModel()
        {
            //Arrange
            bool methodCalled = false;
            CodeGeneratorModel invokedModel = null;

            var codeGenInstance = new CodeGeneratorSample((model) =>
            {
                methodCalled = true;
                invokedModel = model;
            });

            var serviceProviderMock = new Mock<IServiceProvider>();
            var generatorMock = new Mock<CodeGeneratorDescriptor>(typeof(CodeGeneratorSample).GetTypeInfo(),
                serviceProviderMock.Object);

            generatorMock
                .SetupGet(cd => cd.CodeGeneratorInstance)
                .Returns(codeGenInstance);
            generatorMock
                .SetupGet(cd => cd.Name)
                .Returns(typeof(CodeGeneratorSample).Name);

            var actionDescriptor = new ActionDescriptor(generatorMock.Object,
                typeof(CodeGeneratorSample).GetMethod("GenerateCode")); //This is not a perfect unit test as the arrange is using actual instance rather than a mock

            var actionInvoker = new ActionInvoker(actionDescriptor);

            //Act
            actionInvoker.Execute("CodeGeneratorSample StringValuePassed --BoolProperty".Split(' '));

            //Assert
            Assert.True(methodCalled);
            Assert.NotNull(invokedModel);
            Assert.Equal("StringValuePassed", invokedModel.StringProperty);
            Assert.True(invokedModel.BoolProperty);
        }
Example #36
0
 private static Func<Task> InvokeActionWithActionFilters(EventHandlerContext context, CancellationToken cancellationToken, IEventHandlerFilter[] filters, Func<ActionInvoker, Task> innerAction, ActionInvoker state)
 {
     return InvokeHandlerWithHandlerFiltersAsync(context, cancellationToken, filters, () => innerAction(state));
 }
        private HttpResponse Process(HttpRequest request)
        {
            if (request.Method.ToLower() == "head")
            {
                return new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, string.Empty);
            }

            if (request.Method.ToLower() == "options")
            {
                var routes =
                    Assembly.GetEntryAssembly()
                            .GetTypes()
                            .Where(x => x.Name.EndsWith("Controller") && typeof(Controller).IsAssignableFrom(x))
                            .Select(
                                x =>
                                    new
                                    {
                                        x.Name,
                                        Methods = x.GetMethods().Where(m => m.ReturnType == typeof(IActionResult))
                                    })
                            .SelectMany(
                                x => x.Methods.Select(
                                    m => string.Format(
                                        "/{0}/{1}/{{parameter}}",
                                        x.Name.Replace("Controller", string.Empty),
                                        m.Name)))
                            .ToList();

                return new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, string.Join(Environment.NewLine, routes));
            }

            if (new StaticFileHandler().CanHandle(request))
            {
                return new StaticFileHandler().Handle(request);
            }

            if (request.ProtocolVersion.Major <= 3)
            {
                HttpResponse response;
                try
                {
                    var controller = this.CreateController(request);
                    var actionInvoker = new ActionInvoker();
                    var actionResult = actionInvoker.InvokeAction(controller, request.Action);
                    response = actionResult.GetResponse();
                }
                catch (HttpNotFoundException exception)
                {
                    response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotFound, exception.Message);
                }
                catch (Exception exception)
                {
                    response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.InternalServerError, exception.Message);
                }

                return response;
            }

            return new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotImplemented, "Request cannot be handled.");
        }
 private static Func<Task<HandlerResponse>> InvokeActionWithActionFilters(CommandHandlerContext context, CancellationToken cancellationToken, ICommandHandlerFilter[] filters, Func<ActionInvoker, Task<HandlerResponse>> innerAction, ActionInvoker state)
 {
     return InvokeHandlerWithHandlerFiltersAsync(context, cancellationToken, filters, () => innerAction(state));
 }