Esempio n. 1
0
        private List <SelectListItem> GetAvailableSyntaxThemes(string selectedItem)
        {
            var items    = new List <SelectListItem>();
            var basePath = _pathMapper.MapPath("~/Content/codeHighlighter/styles");
            var files    = Directory.GetFiles(basePath, "shCore*.css");

            files.ToList().ForEach(file =>
            {
                var r1    = new Regex(@"shCore([A-Za-z0-9\-]+).css");
                var match = r1.Match(Path.GetFileName(file));
                if (match.Groups[1].Value != string.Empty)
                {
                    var item = new SelectListItem {
                        Text = match.Groups[1].Value, Value = match.Groups[1].Value, Selected = match.Groups[1].Value == selectedItem
                    };
                    items.Add(item);
                }
            });

            var defaultItem = items.Single(i => i.Text == "Default");

            defaultItem.Selected = true;

            return(items);
        }
Esempio n. 2
0
 public SyntaxPossibilities(IPathMapper pathMapper, string selectedBrushes)
 {
     _pathMapper = pathMapper;
     _selectedBrushes = selectedBrushes;
     _basePath = _pathMapper.MapPath("~/Content/codeHighlighter/scripts");
     AddSyntaxPossibilities();
 }
Esempio n. 3
0
 public SyntaxPossibilities(IPathMapper pathMapper, string selectedBrushes)
 {
     _pathMapper      = pathMapper;
     _selectedBrushes = selectedBrushes;
     _basePath        = _pathMapper.MapPath("~/Content/codeHighlighter/scripts");
     AddSyntaxPossibilities();
 }
Esempio n. 4
0
        public static string ReadLog(IPathMapper pathMapper)
        {
            string path = string.Format("{0}\\{1}", pathMapper.MapPath("~/App_Data"), FileName);

            string content = Common.IO.FileHelper.ReadFile(path);

            Common.IO.FileHelper.Delete(path);
            return(content);
        }
Esempio n. 5
0
        public CsvRepository(string source, IPathMapper pathMapper)
        {
            //_source = String.Format(@"Repository/csv/{0}.csv", source);
            _source      = pathMapper.MapPath(source);
            _cultureUsed = new CultureInfo("da-DK");

            if (!File.Exists(_source))
            {
                throw new ArgumentException(String.Format("The requested repository {0} doesn't exist", source));
            }
        }
Esempio n. 6
0
        private static string NormalizePath(IPathMapper pathMapper, string path)
        {
            string retVal;

            if (path.StartsWith("~"))
            {
                retVal = pathMapper.MapPath(path);
            }
            else if (Path.IsPathRooted(path))
            {
                retVal = path;
            }
            else
            {
                retVal  = pathMapper.MapPath("~/");
                retVal += path;
            }

            return(retVal != null?Path.GetFullPath(retVal) : null);
        }
Esempio n. 7
0
        public ActionResult ManageUploads([DefaultValue(1)] int page)
        {
            var basePath     = _pathMapper.MapPath(UploadsBasePath);
            var fileInfoList = new List <FileEntry>();

            var files = Directory.GetFiles(basePath).ToList();

            files.ForEach(file => fileInfoList.Add(GetFileEntry(file)));

            var fileInfoListSorted = fileInfoList.OrderBy(f => f.FileName).ToList();

            var model = new AdminUploadsViewModel
            {
                FileEntries = fileInfoListSorted.Skip((page - 1) * _itemsPerPage).Take(_itemsPerPage).ToList(),
                PagingInfo  = new PagingInformation
                {
                    CurrentPage  = page,
                    ItemsPerPage = _itemsPerPage,
                    TotalItems   = fileInfoList.Count
                },
                OneTimeCode = GetToken(),
                Title       = SettingsRepository.BlogName
            };

            return(View(model));
        }
Esempio n. 8
0
        private static bool DeleteFile(IPathMapper pathMapper)
        {
            try
            {
                var filePath = pathMapper.MapPath("~/Uploads/" + TestFileName);
                File.Delete(filePath);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 9
0
        private static bool DeleteFile(IPathMapper pathMapper)
        {
            try
            {
                var filePath = pathMapper.MapPath("~/Uploads/" + TestFileName);
                File.Delete(filePath);

                return true;
            }
            catch
            {
                return false;
            }
        }
Esempio n. 10
0
        private static bool CreateFile(IPathMapper pathMapper)
        {
            try
            {
                var sWriter = new StreamWriter(pathMapper.MapPath("~/Uploads/" + TestFileName));
                sWriter.WriteLine("Testing sBlog.Net install");
                sWriter.Close();

                return(DeleteFile(pathMapper));
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 11
0
        private static bool CreateFile(IPathMapper pathMapper)
        {
            try
            {
                var sWriter = new StreamWriter(pathMapper.MapPath("~/Uploads/" + TestFileName));
                sWriter.WriteLine("Testing sBlog.Net install");
                sWriter.Close();

                return DeleteFile(pathMapper);
            }
            catch
            {
                return false;
            }
        }
        public static SortedSet <SchemaVersion> GetAvailableScripts(this IPathMapper pathMapper)
        {
            var sortedList = new SortedSet <SchemaVersion>();
            var filePath   = pathMapper.MapPath("~/Sql");

            if (filePath != null)
            {
                var files = Directory.GetFiles(filePath).ToList();
                files.ForEach(f =>
                {
                    var schemaItem = f.Parse();
                    sortedList.Add(schemaItem);
                });
            }
            return(sortedList);
        }
Esempio n. 13
0
        public IStorageProviderConfig ToConfig(JToken config)
        {
            Contract.NotNull(config, nameof(config));

            string dir = config.Value <string>("dir");
            bool?  createIfNotExists = config.Value <bool?>("createIfNotExists");

            if (!Path.IsPathRooted(dir))
            {
                dir = pathMapper.MapPath(dir);
            }

            if (!createIfNotExists.HasValue)
            {
                createIfNotExists = false;
            }

            return(new FileSystemCabinetConfig(dir, createIfNotExists.Value));
        }
        public TranslationResponse Get([FromUri] TranslationRequest request)
        {
            var plugins  = PluginLoader.Load(_mapper.MapPath(ConfigurationManager.AppSettings["PluginsDirectory"]));
            var engine   = new TranslatorEngine(plugins, ConfigurationManager.AppSettings["DefaultLanguage"]);
            var plugin   = engine[request.Language];
            var response = new TranslationResponse();

            if (plugin is NoAvailableLanguagesTranlastor)
            {
                response.Code = HttpStatusCode.NotFound;
            }
            else
            {
                response.Code = HttpStatusCode.OK;
            }
            response.Translation = plugin.Translate(request.Text);
            response.Language    = plugin.LanguageCode;

            return(response);
        }
Esempio n. 15
0
        public void Run(IBootLogger bootLogger, IPathMapper pathMapper)
        {
            var logger = new ServerBootLoggerAdapter(bootLogger);

            logger.Log("Bootstrapper starting...", Category.Info, Priority.None);
            try
            {
                logger.Log("Creating services container " + typeof(UnityServiceLocator).FullName, Category.Debug, Priority.None);
                var serviceLocator = new UnityServiceLocator(null, logger);

                logger.Log("Setting service locator provider", Category.Debug, Priority.None);
                //registrar o ServiceLocator
                ServiceLocator.SetLocatorProvider(() => serviceLocator);

                //registrar o locator
                ServiceLocator.Register <IServiceLocator>(serviceLocator);

                // registrar o path mapper
                ServiceLocator.Register <IPathMapper>(pathMapper);

                var workServicesManager = new WorkerServicesManager();
                workServicesManager.Start();
                ServiceLocator.Register <IWorkerServicesManager>(workServicesManager);

                // registrar o gerenciador de 'EntityStores'
                ServiceLocator.Register <IEntityStoreManager>(new EntityStoreManager());

                // registrar o buffer do logger
                ServiceLocator.Register <LogWriterBufferService, LogWriterBufferService>(true);

                // registrar o factory de logs para o entity store
                ServiceLocator.Register <ILoggerFactory>(new EntityStoreLoggerFactory());

                // registrar o gerenciador de log
                ServiceLocator.Register <ILogManager>(new LogManager());

                // registrar o logger do sistema
                ServiceLocator.GetInstance <ILogManager>().RegisterLogger(logger);

                // registrar o servico de gerenciamento de usuarios
                serviceLocator.Register <IAccountService, AccountService>(true);

                // serviços de autenticacao e autorização
                ServiceLocator.Register <IAuthenticationService, AuthenticationService>(true);
                ServiceLocator.Register <IAuthorizationService, AuthorizationService>(true);


                // registrar o pipeline
                serviceLocator.Register <IPipelineManager, PipelineManager>(true);

                // registrar o worker que fará a gravação do log
                ServiceLocator.GetInstance <IWorkerServicesManager>().RegisterService(
                    "LogWriter",
                    new LogWriterWorkerService(),
                    null);

                //agregador de eventos
                ServiceLocator.Register <IEventAggregator, EventAggregator>(true);

                // controlador de sessoes
                serviceLocator.Register <IClientSessionManager, ClientSessionManager>(true);

                // recursos do cliente
                serviceLocator.Register <IResourceMapService, ResourceMapService>(true);

                //registrar os servicos de modulos
                ServiceLocator.Register <IModuleCatalog>(new DirectoryModuleCatalog2(pathMapper.MapPath("~/bin")));
                ServiceLocator.Register <IModuleInitializer, ModuleInitializer>(true);
                ServiceLocator.Register <IModuleManager, ModuleManager>(true);

                //localizador de controllers mvc
                //ServiceLocator.Register<IMvcControllerTypeLocator, MvcControllerTypeLocator>(true);

                //System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new MvcControllerFactory());

                logger.Log("Loading modules...", Category.Info, Priority.None);
                //carregar os modulos
                ServiceLocator.GetInstance <IModuleManager>().Run();

                logger.Log("Server started", Category.Info, Priority.None);

                ServiceLocator.GetInstance <ILogManager>()
                .GetLogger("START_UP")
                .Log("Server started", Category.Debug, Priority.None);
            }
            catch (Exception ex)
            {
                logger.LogException("Fatal error on server bootstrap", ex, Priority.High);
            }
        }
Esempio n. 16
0
        public static void SetupContainer(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper,
                                          string virtualRoot, string routePrefix, string modulesPhysicalPath)
        {
            container.RegisterInstance(app);

            var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>();

            moduleInitializerOptions.VirtualRoot = virtualRoot;
            moduleInitializerOptions.RoutePrefix = routePrefix;

            //Initialize Platform dependencies
            var connectionString = ConfigurationHelper.GetConnectionStringValue("VirtoCommerce");

            var hangfireOptions = new HangfireOptions
            {
                StartServer              = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.Enabled", true),
                JobStorageType           = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.StorageType", "Memory"),
                DatabaseConnectionString = connectionString,
                WorkerCount              = ConfigurationHelper.GetNullableAppSettingsValue("VirtoCommerce:Jobs.WorkerCount", (int?)null)
            };
            var hangfireLauncher = new HangfireLauncher(hangfireOptions);

            var authenticationOptions = new AuthenticationOptions
            {
                AllowOnlyAlphanumericUserNames = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AllowOnlyAlphanumericUserNames", false),
                RequireUniqueEmail             = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:RequireUniqueEmail", false),

                PasswordRequiredLength          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Password.RequiredLength", 5),
                PasswordRequireNonLetterOrDigit = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Password.RequireNonLetterOrDigit", false),
                PasswordRequireDigit            = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Password.RequireDigit", false),
                PasswordRequireLowercase        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Password.RequireLowercase", false),
                PasswordRequireUppercase        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Password.RequireUppercase", false),

                UserLockoutEnabledByDefault          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:UserLockoutEnabledByDefault", true),
                DefaultAccountLockoutTimeSpan        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:DefaultAccountLockoutTimeSpan", TimeSpan.FromMinutes(5)),
                MaxFailedAccessAttemptsBeforeLockout = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:MaxFailedAccessAttemptsBeforeLockout", 5),

                DefaultTokenLifespan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:DefaultTokenLifespan", TimeSpan.FromDays(1)),

                CookiesEnabled          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)),

                BearerTokensEnabled        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                AccessTokenExpireTimeSpan  = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromMinutes(30)),
                RefreshTokenExpireTimeSpan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.RefreshTokenExpireTimeSpan", TimeSpan.FromDays(30)),
                BearerAuthorizationLimitedCookiePermissions = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.LimitedCookiePermissions", string.Empty),

                HmacEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),

                ApiKeysEnabled                  = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName           = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),

                AuthenticationMode = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:AuthenticationMode", AuthenticationMode.Active),
                AuthenticationType = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:AuthenticationType", DefaultAuthenticationTypes.ApplicationCookie),
                CookieDomain       = ConfigurationHelper.GetAppSettingsValue <string>("VirtoCommerce:Authentication:Cookie:Domain", null),
                CookieHttpOnly     = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:HttpOnly", true),
                CookieName         = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:Name", CookieAuthenticationDefaults.CookiePrefix + DefaultAuthenticationTypes.ApplicationCookie),
                CookiePath         = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:Path", "/"),
                CookieSecure       = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:Secure", CookieSecureOption.SameAsRequest),
                ExpireTimeSpan     = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:ExpireTimeSpan", TimeSpan.FromDays(14)),
                LoginPath          = new PathString(ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:LoginPath", string.Empty)),
                LogoutPath         = new PathString(ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:LogoutPath", string.Empty)),
                ReturnUrlParameter = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:ReturnUrlParameter", CookieAuthenticationDefaults.ReturnUrlParameter),
                SlidingExpiration  = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookie:SlidingExpiration", true),

                AzureAdAuthenticationEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.Enabled", false),
                AzureAdAuthenticationType    = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.AuthenticationType", OpenIdConnectAuthenticationDefaults.AuthenticationType),
                AzureAdAuthenticationCaption = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.Caption", OpenIdConnectAuthenticationDefaults.Caption),
                AzureAdApplicationId         = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.ApplicationId", string.Empty),
                AzureAdTenantId        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.TenantId", string.Empty),
                AzureAdInstance        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.Instance", string.Empty),
                AzureAdDefaultUserType = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:AzureAD.DefaultUserType", "Manager")
            };

            container.RegisterInstance(authenticationOptions);

            InitializePlatform(app, container, pathMapper, connectionString, hangfireLauncher, modulesPhysicalPath, moduleInitializerOptions);

            var moduleManager = container.Resolve <IModuleManager>();
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator();

            // Register URL rewriter for platform scripts
            var scriptsPhysicalPath        = pathMapper.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator();
            var scriptsRelativePath        = MakeRelativePath(applicationBase, scriptsPhysicalPath);
            var platformUrlRewriterOptions = new UrlRewriterOptions();

            platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), "");
            app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath)
            });

            // Register URL rewriter before modules initialization
            if (Directory.Exists(modulesPhysicalPath))
            {
                var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath);

                var urlRewriterOptions = new UrlRewriterOptions();

                foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                {
                    var urlRewriteKey   = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName);
                    var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath);
                    urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue);

                    moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath);
                }

                app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions);
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath)
                });
            }

            container.RegisterInstance(GlobalConfiguration.Configuration);

            // Ensure all modules are loaded
            foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            SwaggerConfig.RegisterRoutes(container);

            // Post-initialize

            // Register MVC areas unless running in the Web Platform Installer mode
            if (IsApplication)
            {
                AreaRegistration.RegisterAllAreas();
            }

            // Register other MVC resources
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            if (IsApplication)
            {
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Security OWIN configuration
            OwinConfig.Configure(app, container);

            hangfireLauncher.ConfigureOwin(app, container);

            RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *");

            var notificationManager = container.Resolve <INotificationManager>();
            var assembly            = typeof(LiquidNotificationTemplateResolver).Assembly;

            notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Registration notification",
                Description          = "This notification is sent by email to a client when he finishes registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.RegistrationNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.RegistrationNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Reset password email notification",
                Description          = "This notification is sent by email to a client upon reset password request",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ResetPasswordNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ResetPasswordNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new TwoFactorEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Two factor authentication",
                Description          = "This notification contains a security token for two factor authentication",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.TwoFactorNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.TwoFactorNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new TwoFactorSmsNotification(container.Resolve <ISmsNotificationSendingGateway>())
            {
                DisplayName          = "Two factor authentication",
                Description          = "This notification contains a security token for two factor authentication",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.TwoFactorNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.TwoFactorNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new ResetPasswordSmsNotification(container.Resolve <ISmsNotificationSendingGateway>())
            {
                DisplayName          = "Reset password sms notification",
                Description          = "This notification is sent by sms to a client upon reset password request",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ResetPasswordSmsNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ResetPasswordSmsNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new ChangePhoneNumberSmsNotification(container.Resolve <ISmsNotificationSendingGateway>())
            {
                DisplayName          = "Change phone number sms notification",
                Description          = "This notification is sent by sms to a client upon change phone number request",
                NotificationTemplate = new NotificationTemplate
                {
                    Body     = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ChangePhoneNumberSmsNotificationTemplateBody.html").ReadToString(),
                    Subject  = assembly.GetManifestResourceStream("VirtoCommerce.Platform.Data.Notifications.Templates.ChangePhoneNumberSmsNotificationTemplateSubject.html").ReadToString(),
                    Language = "en-US",
                }
            });

            //Get initialized modules list sorted by dependency order
            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                                        .Where(m => m.ModuleInstance != null && m.State == ModuleState.Initialized)
                                        .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            // Initialize InstrumentationKey from EnvironmentVariable
            var applicationInsightsInstrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");

            if (!string.IsNullOrEmpty(applicationInsightsInstrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = applicationInsightsInstrumentationKey;
            }

            // https://docs.microsoft.com/en-us/azure/application-insights/app-insights-live-stream#secure-the-control-channel
            // https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/733#issuecomment-349752497
            // https://github.com/Azure/azure-webjobs-sdk/issues/1349
            var applicationInsightsAuthApiKey = Environment.GetEnvironmentVariable("APPINSIGHTS_QUICKPULSEAUTHAPIKEY");

            if (!string.IsNullOrEmpty(applicationInsightsAuthApiKey))
            {
                var module = TelemetryModules.Instance.Modules.OfType <QuickPulseTelemetryModule>().Single();
                if (module != null)
                {
                    module.AuthenticationApiKey = applicationInsightsAuthApiKey;
                }
            }
        }
Esempio n. 17
0
        public static void SetupContainer(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper,
                                          string virtualRoot, string routePrefix, string modulesPhysicalPath)
        {
            container.RegisterInstance(app);

            var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>();

            moduleInitializerOptions.VirtualRoot = virtualRoot;
            moduleInitializerOptions.RoutePrefix = routePrefix;

            //Initialize Platform dependencies
            var connectionString = ConfigurationHelper.GetConnectionStringValue("VirtoCommerce");

            var hangfireOptions = new HangfireOptions
            {
                StartServer              = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.Enabled", true),
                JobStorageType           = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.StorageType", "Memory"),
                DatabaseConnectionString = connectionString,
                WorkerCount              = ConfigurationHelper.GetNullableAppSettingsValue("VirtoCommerce:Jobs.WorkerCount", (int?)null)
            };
            var hangfireLauncher = new HangfireLauncher(hangfireOptions);

            InitializePlatform(app, container, pathMapper, connectionString, hangfireLauncher, modulesPhysicalPath);

            var moduleManager = container.Resolve <IModuleManager>();
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator();

            // Register URL rewriter for platform scripts
            var scriptsPhysicalPath        = pathMapper.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator();
            var scriptsRelativePath        = MakeRelativePath(applicationBase, scriptsPhysicalPath);
            var platformUrlRewriterOptions = new UrlRewriterOptions();

            platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), "");
            app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath)
            });

            // Register URL rewriter before modules initialization
            if (Directory.Exists(modulesPhysicalPath))
            {
                var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath);

                var urlRewriterOptions = new UrlRewriterOptions();

                foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                {
                    var urlRewriteKey   = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName);
                    var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath);
                    urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue);

                    moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath);
                }

                app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions);
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath)
                });
            }

            container.RegisterInstance(GlobalConfiguration.Configuration);

            // Ensure all modules are loaded
            foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            SwaggerConfig.RegisterRoutes(container);

            // Post-initialize

            // Register MVC areas unless running in the Web Platform Installer mode
            if (IsApplication)
            {
                AreaRegistration.RegisterAllAreas();
            }

            // Register other MVC resources
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            if (IsApplication)
            {
                RouteConfig.RegisterRoutes(RouteTable.Routes);
            }

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Security OWIN configuration
            var authenticationOptions = new Core.Security.AuthenticationOptions
            {
                CookiesEnabled             = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval    = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)),
                BearerTokensEnabled        = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                BearerTokensExpireTimeSpan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)),
                HmacEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),
                ApiKeysEnabled                  = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName           = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),
            };

            OwinConfig.Configure(app, container, authenticationOptions);

            hangfireLauncher.ConfigureOwin(app, container);

            RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *");

            var notificationManager = container.Resolve <INotificationManager>();

            notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Registration notification",
                Description          = "This notification is sent by email to a client when he finishes registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Subject  = PlatformNotificationResource.RegistrationNotificationSubject,
                    Body     = PlatformNotificationResource.RegistrationNotificationBody,
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Reset password notification",
                Description          = "This notification is sent by email to a client upon reset password request",
                NotificationTemplate = new NotificationTemplate
                {
                    Subject  = PlatformNotificationResource.ResetPasswordNotificationSubject,
                    Body     = PlatformNotificationResource.ResetPasswordNotificationBody,
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new TwoFactorEmailNotification(container.Resolve <IEmailNotificationSendingGateway>())
            {
                DisplayName          = "Two factor authentication",
                Description          = "This notification contains a security token for two factor authentication",
                NotificationTemplate = new NotificationTemplate
                {
                    Subject  = PlatformNotificationResource.TwoFactorNotificationSubject,
                    Body     = PlatformNotificationResource.TwoFactorNotificationBody,
                    Language = "en-US",
                }
            });

            notificationManager.RegisterNotificationType(() => new TwoFactorSmsNotification(container.Resolve <ISmsNotificationSendingGateway>())
            {
                DisplayName          = "Two factor authentication",
                Description          = "This notification contains a security token for two factor authentication",
                NotificationTemplate = new NotificationTemplate
                {
                    Subject  = PlatformNotificationResource.TwoFactorNotificationSubject,
                    Body     = PlatformNotificationResource.TwoFactorNotificationBody,
                    Language = "en-US",
                }
            });

            //Get initialized modules list sorted by dependency order
            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>())
                                        .Where(m => m.ModuleInstance != null && m.State == ModuleState.Initialized)
                                        .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            var redisConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"];

            // Redis
            if (redisConnectionString != null && !string.IsNullOrEmpty(redisConnectionString.ConnectionString))
            {
                // Cache
                RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString.ConnectionString));

                // SignalR
                // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues
                GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString.ConnectionString, "VirtoCommerce.Platform.SignalR"));
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();

            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration {
                EnableJavaScriptProxies = false
            };

            app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration);

            // Initialize InstrumentationKey from EnvironmentVariable
            var appInsightKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");

            if (!string.IsNullOrEmpty(appInsightKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = appInsightKey;
            }
        }
Esempio n. 18
0
 private static bool ThemeExists(string themeName, IPathMapper pathMapper)
 {
     var requiredFolder = pathMapper.MapPath(string.Format("~/Themes/{0}", themeName));
     return System.IO.Directory.Exists(requiredFolder);
 }
Esempio n. 19
0
        private bool MasterExists(string themeName)
        {
            var requiredFile = string.Format("{0}\\{1}.cshtml", _pathMapper.MapPath(string.Format("~/Themes/{0}", themeName)), ExpectedMasterName);

            return(System.IO.File.Exists(requiredFile));
        }
Esempio n. 20
0
        public void Run(IBootLogger bootLogger, IPathMapper pathMapper)
        {
            var logger = new ServerBootLoggerAdapter(bootLogger);
            logger.Log("Bootstrapper starting...", Category.Info, Priority.None);
            try
            {
                logger.Log("Creating services container " + typeof(UnityServiceLocator).FullName, Category.Debug, Priority.None);
                var serviceLocator = new UnityServiceLocator(null, logger);

                logger.Log("Setting service locator provider", Category.Debug, Priority.None);
                //registrar o ServiceLocator
                ServiceLocator.SetLocatorProvider(() => serviceLocator);

                //registrar o locator
                ServiceLocator.Register<IServiceLocator>(serviceLocator);

                // registrar o path mapper
                ServiceLocator.Register<IPathMapper>(pathMapper);

                var workServicesManager = new WorkerServicesManager();
                workServicesManager.Start();
                ServiceLocator.Register<IWorkerServicesManager>(workServicesManager);

                // registrar o gerenciador de 'EntityStores'
                ServiceLocator.Register<IEntityStoreManager>(new EntityStoreManager());

                // registrar o buffer do logger
                ServiceLocator.Register<LogWriterBufferService, LogWriterBufferService>(true);

                // registrar o factory de logs para o entity store
                ServiceLocator.Register<ILoggerFactory>(new EntityStoreLoggerFactory());

                // registrar o gerenciador de log
                ServiceLocator.Register<ILogManager>(new LogManager());

                // registrar o logger do sistema
                ServiceLocator.GetInstance<ILogManager>().RegisterLogger(logger);

                // registrar o servico de gerenciamento de usuarios
                serviceLocator.Register<IAccountService, AccountService>(true);

                // serviços de autenticacao e autorização
                ServiceLocator.Register<IAuthenticationService, AuthenticationService>(true);
                ServiceLocator.Register<IAuthorizationService, AuthorizationService>(true);

                // registrar o pipeline
                serviceLocator.Register<IPipelineManager, PipelineManager>(true);

                // registrar o worker que fará a gravação do log
                ServiceLocator.GetInstance<IWorkerServicesManager>().RegisterService(
                    "LogWriter",
                    new LogWriterWorkerService(),
                    null);

                //agregador de eventos
                ServiceLocator.Register<IEventAggregator, EventAggregator>(true);

                // controlador de sessoes
                serviceLocator.Register<IClientSessionManager, ClientSessionManager>(true);

                // recursos do cliente
                serviceLocator.Register<IResourceMapService, ResourceMapService>(true);

                //registrar os servicos de modulos
                ServiceLocator.Register<IModuleCatalog>(new DirectoryModuleCatalog2(pathMapper.MapPath("~/bin")));
                ServiceLocator.Register<IModuleInitializer, ModuleInitializer>(true);
                ServiceLocator.Register<IModuleManager, ModuleManager>(true);

                //localizador de controllers mvc
                //ServiceLocator.Register<IMvcControllerTypeLocator, MvcControllerTypeLocator>(true);

                //System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new MvcControllerFactory());

                logger.Log("Loading modules...", Category.Info, Priority.None);
                //carregar os modulos
                ServiceLocator.GetInstance<IModuleManager>().Run();

                logger.Log("Server started", Category.Info, Priority.None);

                ServiceLocator.GetInstance<ILogManager>()
                    .GetLogger("START_UP")
                    .Log("Server started", Category.Debug, Priority.None);
            }
            catch (Exception ex)
            {
                logger.LogException("Fatal error on server bootstrap", ex, Priority.High);
            }
        }
Esempio n. 21
0
        private string GetMailerTemplatePath(string text, string templateName)
        {
            var path = _path.MapPath(string.Format("mailtemplate/{0}/{1}.{2}", "default", templateName, text));

            return(path);
        }
Esempio n. 22
0
 public static bool MasterExists(this string themeName, IPathMapper pathMapper, string expectedMasterName)
 {
     var requiredFile = string.Format("{0}\\{1}.cshtml", pathMapper.MapPath(string.Format("~/Themes/{0}", themeName)), expectedMasterName);
     return System.IO.File.Exists(requiredFile);
 }
Esempio n. 23
0
        private static bool ThemeExists(string themeName, IPathMapper pathMapper)
        {
            var requiredFolder = pathMapper.MapPath(string.Format("~/Themes/{0}", themeName));

            return(System.IO.Directory.Exists(requiredFolder));
        }
Esempio n. 24
0
        public static bool MasterExists(this string themeName, IPathMapper pathMapper, string expectedMasterName)
        {
            var requiredFile = string.Format("{0}\\{1}.cshtml", pathMapper.MapPath(string.Format("~/Themes/{0}", themeName)), expectedMasterName);

            return(System.IO.File.Exists(requiredFile));
        }