Esempio n. 1
0
        public FunqUseCase()
        {
            this._container = new Funq.Container();

            this._container.DefaultReuse = Funq.ReuseScope.None;

            this._container.Register<IWebApp>(
                c => new WebApp(
                         c.Resolve<IAuthenticator>(),
                         c.Resolve<IStockQuote>()));

            this._container.Register<IAuthenticator>(
                c => new Authenticator(
                         c.Resolve<ILogger>(),
                         c.Resolve<IErrorHandler>(),
                         c.Resolve<IDatabase>()));

            this._container.Register<IStockQuote>(
                c => new StockQuote(
                         c.Resolve<ILogger>(),
                         c.Resolve<IErrorHandler>(),
                         c.Resolve<IDatabase>()));

            this._container.Register<ILogger>(
                c => new Logger());

            this._container.Register<IErrorHandler>(
                c => new ErrorHandler(
                         c.Resolve<ILogger>()));

            this._container.Register<IDatabase>(
                c => new Database(
                         c.Resolve<ILogger>(),
                         c.Resolve<IErrorHandler>()));
        }
Esempio n. 2
0
        // This method is invoked when the application has loaded its UI and its ready to run
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            var container = new Funq.Container();
            Tepeyac.Core.Registry.Register(container);

            container.Register<IFiber>("GuiFiber", c =>
            {
                var executor =
                    c.Resolve<IExecutor>() ??
                    new Executor();
                var fiber = new MonoTouchFiber(executor);
                fiber.Start();

                return fiber;
            });

            container.Register<ILauncher>(c =>
                new Tepeyac.UI.MonoTouch.Launcher());

            var view = new BurritoDayView(container);
            window.AddSubview(view.View);
            window.MakeKeyAndVisible();

            return true;
        }
Esempio n. 3
0
        static void Main()
        {
            LogManager.LogFactory = new Log4NetFactory(@"\_config\log4net\log4net.xml");

            Container = new Funq.Container();
            Container.InitializeContainer();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MDIParent());
        }
        public override void Configure(Container container)
        {
            container.Adapter = new StructureMapContainerAdapter();

            SetConfig(new EndpointHostConfig
            {
                WebHostUrl = ConfigurationManager.AppSettings.Get("REST_ServiceURL"),
                GlobalResponseHeaders = {
                                           {"Access-Control-Allow-Origin", "*"},
                                           {"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"},
                                           {"Access-Control-Allow-Headers", "X-File-Name, X-File-Type, X-File-Size"}
                                   },
                CustomHttpHandlers = {
                                        { HttpStatusCode.NotFound, new RazorHandler("/notfound") },
                                        { HttpStatusCode.Forbidden, new RazorHandler("/forbidden") }
                                   },
            });

            Plugins.Add(new CorsFeature());
            Plugins.Add(new RazorFormat());
            Plugins.Add(new SwaggerFeature());
        }
Esempio n. 5
0
        private void WireupSqliteTestserver(Funq.Container container)
        {
            Container = container;

            container.Register<SqliteConfig> (c => {
                var test_db_file = "/tmp/rainy-test.db";
                if (File.Exists (test_db_file))
                    File.Delete (test_db_file);

                SqliteConfig cnf = new SqliteConfig () {
                    File = test_db_file
                };
                return cnf;
            });
            container.Register<IDbConnectionFactory> (c => {
                var connection_string = container.Resolve<SqliteConfig> ().ConnectionString;
                return new OrmLiteConnectionFactory (connection_string, SqliteDialect.Provider);
            });
        }
Esempio n. 6
0
        private void WireupPostgresServer(Funq.Container container)
        {
            Container = container;

            container.Register<PostgreConfig> (c => {
                var cnf = new PostgreConfig {
                    Host = "localhost",
                    Username = "******",
                    Password = "******",
                    Port = 5432,
                    Database = "rainy"
                };
                return cnf;
            });

            container.Register<IDbConnectionFactory> (c => {
                var connection_string = container.Resolve<PostgreConfig> ().ConnectionString;
                return new OrmLiteConnectionFactory (connection_string, PostgreSqlDialect.Provider);
            });
        }
Esempio n. 7
0
        public override void Configure(Funq.Container container)
        {
            this.ComposeObjectGraph(container);

            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            Plugins.Add(new SwaggerFeature());

            // register our custom exception handling
            this.ExceptionHandler        = Rainy.ErrorHandling.ExceptionHandler.CustomExceptionHandler;
            this.ServiceExceptionHandler = Rainy.ErrorHandling.ExceptionHandler.CustomServiceExceptionHandler;

            string swagger_path;

            if (JsonConfig.Config.Global.Development)
            {
                swagger_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../swagger-ui/");
            }
            else
            {
                swagger_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "swagger-ui/");
            }
            var swagger_handler = new FilesystemHandler("/swagger-ui/", swagger_path);

            IHttpHandlerDecider uihandler;
            IHttpHandlerDecider fontshandler = null;

            if (JsonConfig.Config.Global.Development)
            {
                var webui_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../../Rainy.UI/dist/");
                uihandler = (IHttpHandlerDecider) new FilesystemHandler("/", webui_path);
                var fonts_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../../Rainy.UI/dist/fonts/");
                fontshandler = (IHttpHandlerDecider) new FilesystemHandler("/fonts/", fonts_path);
            }
            else
            {
                uihandler = (IHttpHandlerDecider) new EmbeddedResourceHandler("/", this.GetType().Assembly, "Rainy.WebService.Admin.UI");
            }

            this.RequestFilters.Add((req, resp, dto) => {
                if (req.HttpMethod == "OPTIONS")
                {
                    resp.StatusCode = 200;
                    resp.End();
                }
            });

            // BUG HACK
            // GlobalResponseHeaders are not cleared between creating instances of a new config
            // this will be fatal (duplicate key error) for unit tests so we clear the headers
            EndpointHostConfig.Instance.GlobalResponseHeaders.Clear();

            var endpoint_config = new EndpointHostConfig {
                EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //DefaultRedirectPath = "/admin/",

                // not all tomboy clients send the correct content-type
                // so we force application/json
                DefaultContentType = ContentType.Json,

                RawHttpHandlers =
                {
                    uihandler.CheckAndProcess,
                    fontshandler.CheckAndProcess,
                    swagger_handler.CheckAndProcess
                },

                // enable cors
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                                    },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"      },
                    // time in seconds preflight responses can be cached by the client
                    { "Access-Control-Max-Age",       "1728000"                              },
//					{ "Access-Control-Max-Age", "1" },

                    // the Authority header must be whitelisted; it is sent be the rainy-ui
                    // for authentication
                    { "Access-Control-Allow-Headers", "Content-Type, Authority, AccessToken" },
                },
            };

            endpoint_config.AddMaxAgeForStaticMimeTypes["text/html"]       = new TimeSpan(1, 0, 0);
            endpoint_config.AddMaxAgeForStaticMimeTypes["text/css"]        = new TimeSpan(1, 0, 0);
            endpoint_config.AddMaxAgeForStaticMimeTypes["text/javascript"] = new TimeSpan(1, 0, 0);
            SetConfig(endpoint_config);
        }
Esempio n. 8
0
        // http://localhost:5000/auth/[email protected]&&password=!Abc1234
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            SetConfig(new HostConfig
            {
                AddRedirectParamsToQueryString = true,
                //DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false),
                DebugMode = true,
//                UseSameSiteCookies = true, // prevents OAuth providers which use Sessions like Twitter from working
                UseSecureCookies            = true,
                AdminAuthSecret             = "secretz",
                CompressFilesWithExtensions = { "js", "css" },
            });

            RegisterService <GetFileService>();

            Plugins.Add(new GrpcFeature(App));

            // enable server-side rendering, see: https://sharpscript.net
            Plugins.Add(new SharpPagesFeature {
                ScriptMethods = { new CustomScriptMethods() }
            });

            Plugins.Add(new ServerEventsFeature());
            Plugins.Add(new LispReplTcpServer {
//                RequireAuthSecret = true,
                AllowScriptingOfAllTypes = true,
            });

            ConfigurePlugin <UiFeature>(feature => {
                feature.Info.BrandIcon.Uri = "https://vuejs.org/images/logo.svg";
            });

            //not needed for /wwwroot/ui
            //Plugins.AddIfDebug(new HotReloadFeature());

            Plugins.Add(new RazorFormat()); // enable ServiceStack.Razor

            var cache = container.Resolve <ICacheClient>();

            Plugins.Add(new ValidationFeature());

//            Svg.CssFillColor["svg-auth"] = "#ccc";
            Svg.CssFillColor["svg-icons"] = "#e33";

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound]  = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Forbidden] = new SharpPageHandler("/forbidden");

            Svg.Load(RootDirectory.GetDirectory("/assets/svg"));

            Plugins.Add(new PostmanFeature());

            var nativeTypesFeature = GetPlugin <NativeTypesFeature>();

            nativeTypesFeature
            .ExportAttribute <BindableAttribute>(attr => {
                var metaAttr = nativeTypesFeature.GetGenerator().ToMetadataAttribute(attr);
                return(metaAttr);
            });


            CSharpGenerator.TypeFilter = (type, args) => {
                if (type == "ResponseBase`1" && args[0] == "Dictionary<String,List`1>")
                {
                    return("ResponseBase<Dictionary<string,List<object>>>");
                }
                return(null);
            };

            TypeScriptGenerator.TypeFilter = (type, args) => {
                if (type == "ResponseBase`1" && args[0] == "Dictionary<String,List`1>")
                {
                    return("ResponseBase<Map<string,Array<any>>>");
                }
                return(null);
            };

            TypeScriptGenerator.DeclarationTypeFilter = (type, args) => {
                return(null);
            };


            //GetPlugin<SvgFeature>().ValidateFn = req => Config.DebugMode; // only allow in DebugMode
        }
Esempio n. 9
0
 protected abstract void Configure(Funq.Container container);
Esempio n. 10
0
 public override void Configure(Funq.Container container)
 {
     //ServiceStack internally uses its own IoC
     //By implementing an adapter, the calls are passed to the Microsoft.Extensions.DependencyInjection
     container.Adapter = new MicrosoftDependencyInjectionAdapter(_serviceProvider);
 }
Esempio n. 11
0
 protected override void Configure(Funq.Container container)
 {
 }
Esempio n. 12
0
 public override void Configure(Funq.Container container)
 {
 }
Esempio n. 13
0
        /// <summary>
        /// Configures the specified container.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Funq.Container container)
        {
            //new EnumSerializerConfigurator().WithAssemblies(new List<Assembly> { typeof(HierarchyNode).Assembly }).WithNullableEnumSerializers().Configure();
            //  this.Plugins.Add(new ValidationFeature());
            this.ConfigureSerialization();

            //var dialect = new SqlServerOrmLiteDialectProvider();
            // var dialect = SqlServerDialect.Provider;
            //UTC nakoniec nezapinam, mame vlastny serializer vid EgovAppHost;
            //dialect.EnsureUtc(true);
            // Kvôli lepsej konfigurovatelnosti pouzijem MSSql Provider - ak bude cas, potvrdte/vyvratte mi tento nazor
            // SqlServerDialect.Provider

            container.Register <IDbConnectionFactory>(c => new MultiDbFactory(new OrmLiteConnectionFactory(AppSettings.GetString("ConnectionStrings:EsamConnString"), new SqlServerOrmLiteDialectProvider())));

            var RedisUri = HostContext.AppSettings.GetString("RedisUri");

            if (RedisUri.Contains(","))
            {
                container.Register <IRedisClientsManager>(new RedisSentinel(RedisUri.Split(','))
                {
                    RedisManagerFactory = (master, slaves) => new RedisManagerPool(master),
#if PROD
                    HostFilter = host => "Der3dsTR6_56ff@{0}".Fmt(host)
#endif
                }.Start());
            }
            else
            {
                container.Register <IRedisClientsManager>(new RedisManagerPool(RedisUri));
            }
            container.Register <IServerEvents>(c => new RedisServerEvents(c.Resolve <IRedisClientsManager>()));
            container.Resolve <IServerEvents>().Start();


            ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                //log your exceptions here

                var response = WebEasErrorHandling.CreateErrorResponse(httpReq, request, exception);

                if (response.Response is Exceptions.WebEasResponseStatus)
                {
#if DEBUG
                    ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}http://localhost:85/esam/api/pfe/lll/{exception.GetIdentifier()}";
#elif DEVELOP
                    ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-dev.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}";
#elif DEVELOPCRM
                    ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-crm.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}";
#elif ITP
                    ((Exceptions.WebEasResponseStatus)response.Response).DetailMessage += $"{Environment.NewLine}https://esam-test.datalan.sk/esam/api/pfe/lll/{exception.GetIdentifier()}";
#endif
                }

                return(response);
            });

            //Handle Unhandled Exceptions occurring outside of Services
            //E.g. Exceptions during Request binding or in filters:
            //this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) => {
            //res.Write($"Error: {ex.GetType().Name}: {ex.Message}");
            //res.EndRequest(skipHeaders: true);
            //});
        }
Esempio n. 14
0
        public override void Configure(Funq.Container container)
        {
            //LogManager.LogFactory = new DebugLogFactory(); // TODO : remove for production

            JsConfig.DateHandler = JsonDateHandler.ISO8601;
            //JsConfig.EmitCamelCaseNames = true;
            //JsConfig<Ubiquity.Content.SupportedModes>.SerializeFn = val => val.ToString().ToCamelCase();

            container.Register <ICacheClient>(new MemoryCacheClient()
            {
                FlushOnDispose = false
            });
            //var sf = new SessionFeature();

            Plugins.Add(new SessionFeature());
            AuthFeature authService = new AuthFeature(() => new UserSession() /*new AuthUserSession()*/,
                                                      new IAuthProvider[] {
                new UserAuthenticationProvider(),                 //HTML Form post of UserName/Password credentials
            }

                                                      );

            authService.ServiceRoutes = new Dictionary <Type, string[]> {
                { typeof(AuthService), new[] { "/api/auth", "/api/auth/{provider}" } }
            };
            Plugins.Add(authService);
            // enable /requestlogs  for admins
            RequestLogsFeature rlf = new RequestLogsFeature();

            rlf.RequiredRoles = new string[] { "SuperAdmin" };
            Plugins.Add(rlf);

            SetConfig(new EndpointHostConfig {
                DebugMode             = true,  //Show StackTraces in service responses during development
                WriteErrorsToResponse = false, //Disable exception handling
                //DefaultContentType = ContentType.Json, //Change default content type
                AllowJsonpRequests = true,     //Enable JSONP requests
            });

            this.RequestFilters.Add((httpReq, httpResp, requestDto) =>
            {
                /*var sessionId = httpReq.GetCookieValue("user-session");
                 * if (sessionId == null)
                 * {
                 *      httpResp.ReturnAuthRequired();
                 * }*/
            });


            this.ServiceExceptionHandler += ServiceExceptionThrown;

            /*this.ServiceExceptionHandler = (request, ex) => {
             *      ((HttpRequestContext)request).
             * };*/
            // Now add specific routes that directly map to base objects:
            Routes.Add <P2PBackup.Common.Node>("/api/Node/{Id}", "GET,PUT,POST");
            Routes.Add <StorageGroup>("/api/StorageGroups/{Id}", "GET,PUT,POST,DELETE");
            Routes.Add <NodeGroup>("/api/NodeGroups/{Id}", "GET,PUT,POST,DELETE");
            Routes.Add <BackupSet>("/api/BackupSet/{Id}", "GET,PUT,POST");
            Routes.Add <P2PBackup.Common.User>("/api/Users/{Id}", "GET,PUT,POST,DELETE");
            Routes.Add <Hypervisor>("/api/Hypervisors/", "GET");
            Routes.Add <Hypervisor>("/api/Hypervisors/{Id}", "PUT,POST,DELETE");
            Routes.Add <Password>("/api/Passwords/{Id}", "PUT,POST,DELETE");
        }