コード例 #1
0
ファイル: Host.cs プロジェクト: 00mjk/CSharp-Web
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            List <Route> routeTable = new List <Route>();

            IServiceCollection serviceCollection = new ServiceCollection();

            application.ConfigureServices(serviceCollection);

            application.Configure(routeTable);

            AutoRegisterStaticFile(routeTable);

            AutoRegisterRoutes(routeTable, application, serviceCollection);

            Console.WriteLine("Registered routes:");
            foreach (var route in routeTable)
            {
                Console.WriteLine($"{route.Method} " +
                                  $"{route.Path}");
            }

            Console.WriteLine();

            Console.WriteLine("Requests:");

            IHttpServer server = new HttpServer(routeTable);

            await server.StartAsync(port);
        }
コード例 #2
0
        private static void AutoRegisterRoutes(ServerRoutingTable routingTable, IMvcApplication application, IServiceCollection serviceCollection)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                              .Where(myType => myType.IsClass &&
                                     !myType.IsAbstract &&
                                     myType.IsSubclassOf(typeof(Controller)));

            foreach (var controller in controllers)
            {
                var getMethods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(
                    method => method.CustomAttributes.Any(
                        ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttribute))));

                foreach (var methodInfo in getMethods)
                {
                    var httpAttribute = (HttpAttribute)methodInfo.GetCustomAttributes(true)
                                        .FirstOrDefault(ca =>
                                                        ca.GetType().IsSubclassOf(typeof(HttpAttribute)));

                    if (httpAttribute == null)
                    {
                        continue;
                    }

                    routingTable.Add(httpAttribute.Method, httpAttribute.Path,
                                     (request) => ExecuteAction(controller, methodInfo, request, serviceCollection));
                    Console.WriteLine($"Route registered: {controller.Name}.{methodInfo.Name} => {httpAttribute.Method} => {httpAttribute.Path}");
                }
            }
        }
コード例 #3
0
        private static IEnumerable <string> GetNamespaces(IMvcApplication mvcApplication)
        {
            if (mvcApplication.FileExists("~/Views/Web.config"))
            {
                var virtualContent = mvcApplication.GetVirtualContent("~/Views/Web.config");
                var doc            = new XmlDocument();
                using (var s = XmlReader.Create(virtualContent.Open()))
                {
                    doc.Load(s);

                    if (doc.DocumentElement != null)
                    {
                        var nodes = doc.DocumentElement
                                    .SelectNodes("/configuration/system.web.webPages.razor/pages/namespaces/add");
                        if (nodes != null)
                        {
                            foreach (XmlNode n in nodes)
                            {
                                if (n.Attributes != null)
                                {
                                    var ns = n.Attributes["namespace"].Value;
                                    if (!ns.Equals("System.Web.Mvc.Html") && !ns.Equals("System.Web.Optimization"))
                                    {
                                        yield return(ns);
                                    }
                                }
                            }
                        }
                    }
                }
                yield return("Xania.AspNet.Razor.Html");
            }
            else
            {
                var defaultList = new[]
                {
                    "System",
                    "System.Collections.Generic",
                    "System.Linq",
                    "System.Web.Mvc",
                    "System.Web.Mvc.Ajax",
                    "Xania.AspNet.Razor.Html",
                    "System.Web.Routing"
                };

                foreach (var ns in defaultList)
                {
                    yield return(ns);
                }
            }

            var auth = mvcApplication.Assemblies.Any(a => a.EndsWith("Microsoft.Web.WebPages.OAuth.dll"));

            if (auth)
            {
                yield return("DotNetOpenAuth.AspNet");

                yield return("Microsoft.Web.WebPages.OAuth");
            }
        }
コード例 #4
0
        private static void AutoRegisterRoutes(ServerRoutingTable table, IMvcApplication application, IServiceCollection serviceCollection)
        {
            //Get all controllers
            var controllers = application.GetType().Assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract && t.IsSubclassOf(typeof(Controller)));


            //Go through all the controllers
            foreach (var controller in controllers)
            {
                //Take all the methods of every controller
                var getMethods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(method => method.CustomAttributes.Any(ca => ca.AttributeType.IsSubclassOf(typeof(HttpAttribute))));

                //Go trough all the methods of the controller
                foreach (var methodInfo in getMethods)
                {
                    //Get the custom HttpAttribute of the method GET or POST (for now...)
                    var httpAttribute = (HttpAttribute)methodInfo.GetCustomAttributes(true).FirstOrDefault(x => x.GetType().IsSubclassOf(typeof(HttpAttribute)));

                    if (httpAttribute == null)
                    {
                        continue;
                    }

                    //Add to the routing table (HttpMethod (from the HttpAttribute), the path (from the HttpAttribute) and Invoke a specific Action that accepts Request and returns a Response)
                    table.Add(httpAttribute.Mehtod, httpAttribute.Path, (request) => ExecuteAction(controller, methodInfo, request, serviceCollection));
                }
            }
        }
コード例 #5
0
        private static void UseMvc(HttpServerSimulator server, IMvcApplication mvcApplication)
        {
            SimulatorHelper.InitializeMembership();

            server.Use(httpContext =>
            {
                var action = new HttpControllerAction(mvcApplication, httpContext);
                var executionContext = action.GetExecutionContext();

                if (executionContext != null)
                {
                    var actionResult = action.GetAuthorizationResult(executionContext);

                    if (actionResult == null)
                    {
                        action.ValidateRequest(executionContext);
                        actionResult = action.GetActionResult(executionContext);
                    }

                    actionResult.ExecuteResult(executionContext.ControllerContext);
                    return true;
                }

                return false;
            });
        }
コード例 #6
0
        private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable)
        {
            var controllers =
                application.GetType().Assembly.GetTypes().Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type));

            foreach (var controllerType in controllers)
            {
                //TODO: Remove ToString from Info Controller
                var actions = controllerType
                              .GetMethods(BindingFlags.DeclaredOnly
                                          | BindingFlags.Public
                                          | BindingFlags.Instance)
                              .Where(x => !x.IsSpecialName && x.DeclaringType == controllerType)
                              .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    string path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{action.Name}";

                    var attribute = action.GetCustomAttributes()
                                    .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute;

                    var httpMethod = HttpRequestMethod.Get;
                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path, request =>
                    {
                        var controllerInstance = Activator.CreateInstance(controllerType);
                        ((Controller)controllerInstance).Request = request;
                        var controllerPrincipal = ((Controller)controllerInstance).User;

                        //Security Authorization TODO: refactor this
                        var authorizeAttribute = action.GetCustomAttributes().LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute;

                        if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal))
                        {
                            //TODO: redirect to configured Url
                            return(new HttpResponse(HttpResponseStatusCode.Forbidden));
                        }

                        var response = action.Invoke(controllerInstance, new object[0]) as ActionResult;

                        return(response);
                    });
                }
            }
        }
コード例 #7
0
        // /{controller}/{action}/
        private static void AutoRegisterActionRoutes(IList <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                              .Where(type => type.IsSubclassOf(typeof(Controller)) && !type.IsAbstract);

            foreach (var controller in controllers)
            {
                var actions = controller.GetMethods()
                              .Where(x => !x.IsSpecialName &&
                                     !x.IsConstructor &&
                                     x.IsPublic &&
                                     x.DeclaringType == controller);
                foreach (var action in actions)
                {
                    string url = "/" + controller.Name.Replace("Controller", string.Empty) + "/" + action.Name;

                    var attribute = action.GetCustomAttributes()
                                    .FirstOrDefault(x => x.GetType()
                                                    .IsSubclassOf(typeof(HttpMethodAttribute)))
                                    as HttpMethodAttribute;
                    var httpActionType = HttpMethodType.Get;
                    if (attribute != null)
                    {
                        httpActionType = attribute.Type;
                        if (attribute.Url != null)
                        {
                            url = attribute.Url;
                        }
                    }

                    routeTable.Add(new Route(httpActionType, url, (request) => InvokeAction(request, serviceCollection, controller, action)));
                }
            }
        }
コード例 #8
0
        public static async Task StartAsync(IMvcApplication application)
        {
            IList <Route> routeTable = new List <Route>();

            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.Add <ILogger, ConsoleLogger>();

            application.ConfigureServices(serviceCollection);
            application.Configure(routeTable);
            AutoRegisterStaticFilesRoutes(routeTable);
            AutoRegisterActionRoutes(routeTable, application, serviceCollection);

            var logger = serviceCollection.CreateInstance <ILogger>();

            logger.Log("Registered routes:");
            foreach (var route in routeTable)
            {
                logger.Log(route.ToString());
            }

            logger.Log(string.Empty);
            logger.Log("Requests:");
            var httpServer = new HttpServer(80, routeTable, logger);
            await httpServer.StartAsync();
        }
コード例 #9
0
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            // TODO: {controller}/{action}/{id}
            List <Route>       routeTable        = new List <Route>();
            IServiceCollection serviceCollection = new ServiceCollection();

            application.ConfigureServices(serviceCollection);
            application.Configure(routeTable);

            AutoRegisterStaticFile(routeTable);
            AutoRegisterRoutes(routeTable, application, serviceCollection);

            Console.WriteLine("Registered routes:");
            foreach (var route in routeTable)
            {
                Console.WriteLine($"{route.Method} {route.Path}");
            }

            Console.WriteLine();
            Console.WriteLine("Requests:");
            IHttpServer server = new HttpServer(routeTable);

            //Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "http://localhost/");
            await server.StartAsync(port);
        }
コード例 #10
0
        private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection)
        {
            var controllerTypes = application.GetType().Assembly.GetTypes()
                                  .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Controller)));

            foreach (var controllerType in controllerTypes)
            {
                var methods = controllerType.GetMethods()
                              .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType &&
                                     !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName);
                foreach (var method in methods)
                {
                    var url = "/" + controllerType.Name.Replace("Controller", string.Empty)
                              + "/" + method.Name;

                    var attribute = method.GetCustomAttributes(false)
                                    .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute)))
                                    .FirstOrDefault() as BaseHttpAttribute;

                    var httpMethod = HttpMethod.Get;

                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (!string.IsNullOrEmpty(attribute?.Url))
                    {
                        url = attribute.Url;
                    }

                    routeTable.Add(new Route(url, httpMethod, request => ExecuteAction(request, controllerType, method, serviceCollection)));
                }
            }
        }
コード例 #11
0
        public static async Task CreateHostAsync(IMvcApplication application, int post = 80)
        {
            List <Route>       routeTable        = new List <Route>();
            IServiceCollection serviceCollection = new ServiceCollection();

            AutoRegisterStaticFiles(routeTable);

            application.ConfigureServices(serviceCollection);
            application.Configure(routeTable);

            AutoRegisterRoutes(routeTable, application, serviceCollection);

            Console.WriteLine("Registered routes:");
            foreach (var route in routeTable)
            {
                Console.WriteLine($"{route.Method} => {route.Path}");
            }
            Console.WriteLine();
            Console.WriteLine("Requests:");

            IHttpServer server = new HttpServer(routeTable);

            //If we want to auto-start the HomePage or any other page
            //Process.Start(@"C:\Program Files\Mozilla Firefox\firefox.exe", "http://localhost/");
            await server.StartAsync(80);
        }
コード例 #12
0
ファイル: Server.cs プロジェクト: DDeveloperBG/Tasks
        public static async Task RunAsync(IMvcApplication application, int port)
        {
            ServerRoutingTable = new ServerRoutingTable();
            IServiceCollection serviceCollection = new ServiceCollection();

            application.ConfigureServices(serviceCollection);
            application.Configure(ServerRoutingTable);

            ServerRoutingTable
            .LoadControllers(application.GetType().Assembly, serviceCollection)
            .LoadStaticFiles();

            Console.WriteLine(string.Join(Environment.NewLine, ServerRoutingTable.GetAllRouteNames()));

            TcpListener listener = new TcpListener(IPAddress.Parse(LocalhostIpAddress), port);

            listener.Start();
            IsRunning = true;

            Console.WriteLine($"Server started at http://{LocalhostIpAddress}:{port}");

            while (IsRunning)
            {
                Console.WriteLine("Waiting for client...");

                var client = await listener.AcceptSocketAsync();

                ListenAsync(client);
            }
        }
コード例 #13
0
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            var routeTable        = new List <Route>();
            var serviceCollection = new ServiceCollection();

            //We pass "application" so we can access the executing assembly ang get all types -> GetTypes().

            application.ConfigureServices(serviceCollection);
            application.Configure(routeTable);

            AutoGenerateStaticFiles(routeTable);
            AutoRegisterRoutes(routeTable, application, serviceCollection);

            //For debugging purposes
            System.Console.WriteLine("All registered routes");
            foreach (var route in routeTable)
            {
                System.Console.WriteLine($"{route.Method} => {route.Path}");
            }

            IHttpServer server = new HttpServer(routeTable);

            //If we don't "await" here, the app will close after receiving the first client. Now, it will keep listening (tcpListener).
            await server.StartAsync(80);
        }
コード例 #14
0
        private static void AutoRegisterRoutes(
            IMvcApplication application,
            IServerRoutingTable serverRoutingTable,
            IServiceProvider serviceProvider)
        {
            var controllers = application
                              .GetType()
                              .Assembly
                              .GetTypes()
                              .Where(type =>
                                     type.IsClass &&
                                     !type.IsAbstract &&
                                     typeof(Controller).IsAssignableFrom(type));

            foreach (var controllerType in controllers)
            {
                var actions = controllerType
                              .GetMethods(
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public |
                    BindingFlags.Instance)
                              .Where(m => !m.IsSpecialName && m.DeclaringType == controllerType)
                              .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    var path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{action.Name}";

                    var attribute = action
                                    .GetCustomAttributes()
                                    .Where(x => x
                                           .GetType()
                                           .IsSubclassOf(typeof(BaseHttpAttribute)))
                                    .LastOrDefault() as BaseHttpAttribute;

                    var httpMethod = HttpRequestMethod.Get;

                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path,
                                           (request) => ProcessRequest(serviceProvider, controllerType, action, request));

                    Console.WriteLine(httpMethod + " " + path);
                }
            }
        }
コード例 #15
0
        public SimulatorActionInvoker(IMvcApplication mvcApplication, ActionExecutionContext actionExecutionContext)
        {
            _filterInfo = mvcApplication.GetFilterInfo(actionExecutionContext.ControllerContext,
                                                       actionExecutionContext.ActionDescriptor);

            _mvcApplication         = mvcApplication;
            _actionExecutionContext = actionExecutionContext;
        }
コード例 #16
0
        public SimulatorActionInvoker(IMvcApplication mvcApplication, ActionExecutionContext actionExecutionContext)
        {
            _filterInfo = mvcApplication.GetFilterInfo(actionExecutionContext.ControllerContext,
                actionExecutionContext.ActionDescriptor);

            _mvcApplication = mvcApplication;
            _actionExecutionContext = actionExecutionContext;
        }
コード例 #17
0
        public static void Initialise(IMvcApplication application)
        {
            //Database.SetInitializer<SetGameContext>(new SetGameDbInitializer());
            var container = BuildUnityContainer(application);

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }
コード例 #18
0
        protected ControllerAction(IMvcApplication mvcApplication, HttpContextBase context = null)
        {
            MvcApplication = mvcApplication;

            Cookies = new Collection <HttpCookie>();
            Session = new Dictionary <string, object>();

            HttpContext = context;
        }
コード例 #19
0
        protected ControllerAction(IMvcApplication mvcApplication, HttpContextBase context = null)
        {
            MvcApplication = mvcApplication;

            Cookies = new Collection<HttpCookie>();
            Session = new Dictionary<string, object>();

            HttpContext = context;
        }
コード例 #20
0
ファイル: WebHost.cs プロジェクト: DKKostadinov/softuni
        public static async Task StartAsync(IMvcApplication application)
        {
            var routeTable = new List <Route>();

            application.ConfigureServices();
            application.Configure(routeTable);
            var httpServer = new HttpServer(80, routeTable);
            await httpServer.StartAsync();
        }
コード例 #21
0
 public void RegisterRoutes(
     ServerRoutingTable routingTable,
     IMvcApplication application,
     MvcFrameworkSettings settings,
     IServiceCollection serviceCollection)
 {
     RegisterStaticFiles(routingTable, settings);
     RegisterActions(routingTable, application, settings, serviceCollection);
     RegisterDefaultRoute(routingTable);
 }
コード例 #22
0
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            List <Route> routeTable = new List <Route>();

            application.configureServices();
            application.Configure(routeTable);

            IHttpServer server = new HttpServer(routeTable);
            await server.StartAsync(port);
        }
コード例 #23
0
        private static void AutoRegisterRoutes(
            IMvcApplication application, IServerRoutingTable serverRoutingTable)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                              .Where(type => type.IsClass && !type.IsAbstract &&
                                     typeof(Controller).IsAssignableFrom(type));

            // TODO: RemoveToString from InfoController
            foreach (var controller in controllers)
            {
                var actions = controller
                              .GetMethods(BindingFlags.DeclaredOnly
                                          | BindingFlags.Public
                                          | BindingFlags.Instance)
                              .Where(x => !x.IsSpecialName && x.DeclaringType == controller);
                foreach (var action in actions)
                {
                    var path      = $"/{controller.Name.Replace("Controller", string.Empty)}/{action.Name}";
                    var attribute = action.GetCustomAttributes().Where(
                        x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute;
                    var httpMethod = HttpRequestMethod.Get;
                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controller.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path, request =>
                    {
                        // request => new UsersController().Login(request)
                        var controllerInstance = Activator.CreateInstance(controller);
                        var response           = action.Invoke(controllerInstance, new[] { request }) as IHttpResponse;
                        return(response);
                    });

                    Console.WriteLine(httpMethod + " " + path);
                }
            }
            // Reflection
            // Assembly
            // typeof(Server).GetMethods()
            // sb.GetType().GetMethods();
            // Activator.CreateInstance(typeof(Server))
            var sb = DateTime.UtcNow;
        }
コード例 #24
0
        public static void Start(IMvcApplication application)
        {
            IServerRoutingTable serverRoutingTable = new ServerRoutingTable();

            AutoRegisterRoutes(application, serverRoutingTable);
            application.ConfigureServices();
            application.Configure(serverRoutingTable);
            var server = new Server(8000, serverRoutingTable);

            server.Run();
        }
コード例 #25
0
 public HomeController(IOptions <RevampCoreSettings> settings, IMvcApplication iMvcApplication)
 {
     RevampCoreSettings = settings.Value;
     mvcApplication     = iMvcApplication;
     _Connect           = new ConnectToDB
     {
         Platform      = RevampCoreSettings.Platform,
         DBConnString  = RevampCoreSettings.DbConnect,
         SourceDBOwner = RevampCoreSettings.SystemDBName
     };
 }
コード例 #26
0
        public static void Start(IMvcApplication application)
        {
            IServiceCollection services = InitializeServices();

            application.ConfigureServices(services);
            application.Configure();
            Server    server = new Server(Constants.ServerHostPort, services);
            MvcEngine engine = new MvcEngine(server);

            engine.Run();
        }
コード例 #27
0
 public LoginController(IOptions <RevampCoreSettings> settings, IMvcApplication iMvcApplication, IHostingEnvironment hostingEnvironment)
 {
     _hostingEnvironment = hostingEnvironment;
     RevampCoreSettings  = settings.Value;
     mvcApplication      = iMvcApplication;
     _Connect            = new ConnectToDB
     {
         Platform      = RevampCoreSettings.Platform,
         DBConnString  = RevampCoreSettings.DbConnect,
         SourceDBOwner = RevampCoreSettings.SystemDBName
     };
 }
コード例 #28
0
        private static IUnityContainer BuildUnityContainer(IMvcApplication application)
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterInstance<IMvcApplication>(application);
            container.RegisterInstance<IModelBinderProvider>(new SetModelBinderProvider());

            RegisterModules(container);

            return container;
        }
コード例 #29
0
        public static async Task StartASync(IMvcApplication application)
        {
            var routeTable = new List <Route>();

            application.ConfigureServices();
            application.Configure(routeTable);
            AutoRegisterStaticFilesRoutes(routeTable);
            AutoRegisterActionRoutes(routeTable, application);

            var httpServer = new HttpServer(80, routeTable);

            await httpServer.StartAsync();
        }
コード例 #30
0
ファイル: Host.cs プロジェクト: Smashcake/csharp-web
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            // TODO: {controller}/{action}/{id}
            List <Route> routeTable = new List <Route>();

            application.ConfigureServices();
            application.Configure(routeTable);

            IHttpServer server = new HttpServer(routeTable);

            // Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "http://localhost/");
            await server.StartAsync(port);
        }
コード例 #31
0
        private static void AutoRegisterRoutes(IMvcApplication application, IServerRoutingTable serverRoutingTable)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                              .Where(type => type.IsClass && !type.IsAbstract &&
                                     typeof(Controller).IsAssignableFrom(type));

            foreach (var controllerType in controllers)
            {
                var actions = controllerType
                              .GetMethods(BindingFlags.DeclaredOnly
                                          | BindingFlags.Public
                                          | BindingFlags.Instance)
                              .Where(x => !x.IsSpecialName && x.DeclaringType == controllerType)
                              .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    var path      = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{action.Name}";
                    var attribute = action.GetCustomAttributes().Where(
                        x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute;
                    var httpMethod = HttpRequestMethod.Get;
                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path,
                                           request =>
                    {
                        var controllerInstance = Activator.CreateInstance(controllerType);
                        var response           = action.Invoke(controllerInstance, new [] { request }) as IHttpResponse;
                        return(response);
                    });


                    Console.WriteLine(httpMethod + " " + path);
                }
            }

            Console.WriteLine(string.Join(Environment.NewLine, serverRoutingTable));
        }
コード例 #32
0
        public static void Start(IMvcApplication application)
        {
            IDependencyContainer container = new DependencyContainer();

            application.ConfigureServices(container);

            var controllerRouter = new HttpRouteHandlingContext(new ControllerRouter(container), new ResourceRouter());

            application.Configure();

            Server server = new Server(HostingPort, controllerRouter);

            server.Run();
        }
コード例 #33
0
        public static async Task CreateHostAsync(IMvcApplication application, int port = 80)
        {
            var routeTable = new List <Route>();

            AutoRegisterStaticFile(routeTable);
            AutoRegisterRoutes(routeTable, application);

            application.ConfigureServices();
            application.Configure(routeTable);

            IHttpServer server = new HttpServer(routeTable);

            await server.StartAsync(port);
        }
コード例 #34
0
        public static void Start(IMvcApplication application)
        {
            IServerRoutingTable serverRoutingTable = new ServerRoutingTable();
            IHttpSessionStorage sessiontorage      = new HttpSessionStorage();

            AutoRegisterRoutes(application, serverRoutingTable);
            application.ConfigureServices();

            application.Configure(serverRoutingTable);

            Server server = new Server(8000, serverRoutingTable, sessiontorage);

            server.Run();
        }
コード例 #35
0
        private static void AutoRegisterRoutes(List <Route> routeTable, IMvcApplication application, IServiceCollection serviceCollection)
        {
            //routeTable.Add(new Route("/cards/add", HttpMethod.Get, new CardsController().Add));
            var controllerTypes = application.GetType().Assembly.GetTypes()
                                  .Where(x => !x.IsAbstract && x.IsClass && x.IsSubclassOf(typeof(Controller))); //we want only the Controller sub-classes

            //Get the methods of each controller
            foreach (var controllerType in controllerTypes)
            {
                //With the current methods, even only x.DeclaringType == controllerType will do the job.
                var methods = controllerType.GetMethods()
                              .Where(x => x.IsPublic && !x.IsStatic && x.DeclaringType == controllerType &&
                                     !x.IsAbstract && !x.IsConstructor && !x.IsSpecialName);

                //For testing purpose
                //Console.WriteLine(controllerType.Name);
                foreach (var method in methods)
                {
                    var url = ($"/{controllerType.Name.Replace("Controller", string.Empty).ToLower()}/{method.Name.ToLower()}");
                    //Console.WriteLine(url);

                    //SUS.MvcFramework.HttpGetAttribute / HttpPostAttribute
                    var customAttribute = method.GetCustomAttributes(false)
                                          .Where(x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute)))
                                          .FirstOrDefault() as BaseHttpAttribute;

                    var httpMethod = HttpMethod.Get;

                    //Check if we've set custom url to the attribute [HttpPost("custom url")]
                    if (!string.IsNullOrWhiteSpace(customAttribute?.Url))
                    {
                        url = customAttribute.Url;
                    }

                    //Check if method is Get or Post
                    if (customAttribute != null)
                    {
                        httpMethod = customAttribute.Method;
                    }

                    if (!string.IsNullOrEmpty(customAttribute?.Url))
                    {
                        url = customAttribute.Url;
                    }

                    //We can afford to cast to HttpResponse since every action returns httpresponse. In ASP Core it will return IActionResult
                    routeTable.Add(new Route(url, httpMethod, request => ExecuteAction(request, controllerType, method, serviceCollection)));
                }
            }
        }
コード例 #36
0
 public RazorViewSimulator(IMvcApplication mvcApplication, IVirtualContent virtualContent, bool isPartialView = false)
 {
     _mvcApplication = mvcApplication;
     _virtualContent = virtualContent;
     _isPartialView = isPartialView;
 }
コード例 #37
0
 public VirtualPathFactorySimulator(IMvcApplication mvcApplication, ViewContext viewContext)
 {
     _mvcApplication = mvcApplication;
     _viewContext = viewContext;
 }
コード例 #38
0
 public ScriptBundles(HttpContextBase context, IMvcApplication mvcApplication) 
     : base(context, mvcApplication)
 {
 }
コード例 #39
0
 public DirectControllerAction(IMvcApplication mvcApplication, ControllerBase controller, ActionDescriptor actionDescriptor)
     : base(mvcApplication)
 {
     Controller = controller;
     ActionDescriptor = actionDescriptor;
 }
コード例 #40
0
 public RazorViewEngineSimulator(IMvcApplication mvcApplication)
 {
     _mvcApplication = mvcApplication;
 }
コード例 #41
0
 public VirtualPathProviderSimulator(IMvcApplication mvcApplication)
 {
     _mvcApplication = mvcApplication;
 }
コード例 #42
0
 protected BundlesBase(HttpContextBase context, IMvcApplication mvcApplication)
 {
     _context = context;
     _mvcApplication = mvcApplication;
 }
コード例 #43
0
 public HttpControllerAction(IMvcApplication mvcApplication)
     : base(mvcApplication, null)
 {
 }
コード例 #44
0
 public HttpControllerAction(IMvcApplication mvcApplication, HttpContextBase context)
     : base(mvcApplication, context)
 {
 }
コード例 #45
0
ファイル: SetGameApp.cs プロジェクト: anton-volodko/game-set
 public SetGameApp(IMvcApplication application)
 {
     _application = application;
 }