// static constructor
        static DriverTestConfiguration()
        {
            var connectionString = CoreTestConfiguration.ConnectionString.ToString();

            var mongoUrl = new MongoUrl(connectionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            if (!clientSettings.WriteConcern.IsAcknowledged)
            {
                clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says
            }

            var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
            if (serverSelectionTimeoutString == null)
            {
                serverSelectionTimeoutString = "10000";
            }
            clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString));
            clientSettings.ClusterConfigurator = cb =>
            {
                var traceSource = new TraceSource("mongodb-tests", SourceLevels.Information);
                traceSource.Listeners.Clear(); // remove the default listener
                var listener = new ConsoleTraceListener();
                traceSource.Listeners.Add(listener);
                cb.TraceWith(traceSource);
            };

            __client = new MongoClient(clientSettings);
            __databaseNamespace = mongoUrl.DatabaseName == null ? CoreTestConfiguration.DatabaseNamespace : new DatabaseNamespace(mongoUrl.DatabaseName);
            __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
        }
예제 #2
0
 // private static methods
 private static MongoClientSettings ParseConnectionString(string connectionString)
 {
     if (connectionString.StartsWith("mongodb://"))
     {
         var url = new MongoUrl(connectionString);
         return MongoClientSettings.FromUrl(url);
     }
     else
     {
         var builder = new MongoConnectionStringBuilder(connectionString);
         return MongoClientSettings.FromConnectionStringBuilder(builder);
     }
 }
        // static constructor
        static DriverTestConfiguration()
        {
            var connectionString = CoreTestConfiguration.ConnectionString.ToString();

            var mongoUrl = new MongoUrl(connectionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            if (!clientSettings.WriteConcern.IsAcknowledged)
            {
                clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says
            }

            clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(500);

            __client = new MongoClient(clientSettings);
            __databaseNamespace = mongoUrl.DatabaseName == null ? CoreTestConfiguration.DatabaseNamespace : new DatabaseNamespace(mongoUrl.DatabaseName);
            __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
        }
예제 #4
0
 /// <summary>
 /// Initializes a new instance of the MongoClient class.
 /// </summary>
 /// <param name="url">The URL.</param>
 public MongoClient(MongoUrl url)
     : this(MongoClientSettings.FromUrl(url))
 {
 }
예제 #5
0
        public BaseRepository(IConfiguration configuration)
        {
            var client = new MongoClient(MongoUrl.Create(configuration.GetConnectionString("DefaultConnection")));

            mongoCollection = client.GetDatabase("gatewayradix").GetCollection <T>(typeof(T).Name);
        }
예제 #6
0
 public TemplateRepository(MongoUrl mongoUrl)
     : base(mongoUrl)
 {
 }
예제 #7
0
        /// <summary>
        /// Gets the <see cref="IMongoDatabase"/> with the specified connection string.
        /// </summary>
        /// <param name="connectionString">The MongoDB connection string.</param>
        /// <returns>An instance of <see cref="IMongoDatabase"/>.</returns>
        public static IMongoDatabase GetDatabaseFromConnectionString(string connectionString)
        {
            var mongoUrl = new MongoUrl(connectionString);

            return(GetDatabaseFromMongoUrl(mongoUrl));
        }
예제 #8
0
        public void RegisterServices(Container container)
        {
            container.RegisterSingle <IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));

            if (Settings.Current.EnableAppStats)
            {
                container.RegisterSingle <IAppStatsClient>(() => new AppStatsClient(Settings.Current.AppStatsServerName, Settings.Current.AppStatsServerPort));
            }
            else
            {
                container.RegisterSingle <IAppStatsClient, NullAppStatsClient>();
            }

            if (Settings.Current.RedisConnectionInfo == null)
            {
                throw new ConfigurationErrorsException("RedisConnectionString was not found in the Web.config.");
            }

            container.RegisterSingle <IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));

            container.RegisterSingle <IRedisClientsManager>(() => new PooledRedisClientManager(Settings.Current.RedisConnectionInfo.ToString()));
            container.Register <ICacheClient>(() => container.GetInstance <IRedisClientsManager>().GetCacheClient());

            container.RegisterSingle <MongoDatabase>(() => {
                if (String.IsNullOrEmpty(Settings.Current.MongoConnectionString))
                {
                    throw new ConfigurationErrorsException("MongoConnectionString was not found in the Web.config.");
                }

                MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);
                var url             = new MongoUrl(Settings.Current.MongoConnectionString);
                string databaseName = url.DatabaseName;
                if (Settings.Current.AppendMachineNameToDatabase)
                {
                    databaseName += String.Concat("-", Environment.MachineName.ToLower());
                }

                MongoServer server = new MongoClient(url).GetServer();
                return(server.GetDatabase(databaseName));
            });

            container.Register <ErrorStatsHelper>();

            container.RegisterSingle <IErrorStackRepository, ErrorStackRepository>();
            container.RegisterSingle <IErrorRepository, ErrorRepository>();
            container.RegisterSingle <IOrganizationRepository, OrganizationRepository>();
            container.RegisterSingle <IJobLockInfoRepository, JobLockRepository>();
            container.RegisterSingle <IJobHistoryRepository, JobHistoryRepository>();
            container.RegisterSingle <IProjectRepository, ProjectRepository>();
            container.RegisterSingle <IUserRepository, UserRepository>();
            container.RegisterSingle <IProjectHookRepository, ProjectHookRepository>();
            container.RegisterSingle <MongoCollection <User> >(() => container.GetInstance <UserRepository>().Collection);

            container.RegisterSingle <IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates"));
            container.RegisterSingle <IMailer, Mailer>();

            container.RegisterSingle <IMessageService, ExceptionlessMqServer>();
            container.Register <IMessageFactory>(() => container.GetInstance <IMessageService>().MessageFactory);

            container.Register <IDependencyResolver, SimpleInjectorCoreDependencyResolver>();

            container.Register <MongoJobHistoryProvider>();
            container.Register <MongoJobLockProvider>();
            container.Register <MongoMachineJobLockProvider>();
            container.Register <StartMqJob>();
            container.Register <ErrorSignatureFactory>();
            container.Register <StripeEventHandler>();
            container.RegisterSingle <BillingManager>();
            container.RegisterSingle <DataHelper>();
        }
예제 #9
0
 public RoleStore(MongoUrl mongoUrl)
     : base(mongoUrl)
 {
 }
        public void TestFromUrlWithMongoDBX509_without_username()
        {
            var url = new MongoUrl("mongodb://localhost/?authMechanism=MONGODB-X509");
            var settings = MongoClientSettings.FromUrl(url);

            var credential = settings.Credentials.Single();
            Assert.Equal("MONGODB-X509", credential.Mechanism);
            Assert.Equal(null, credential.Username);
            Assert.IsType<ExternalEvidence>(credential.Evidence);
        }
예제 #11
0
 public MongoDatabaseFactory(string connectionString)
 {
     ConnectionString = connectionString;
     DBName           = MongoUrl.Create(connectionString).DatabaseName;
 }
예제 #12
0
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, GrandConfig config)
        {
            //HTTP context and other related stuff
            //builder.Register(c =>
            //    //register FakeHttpContext when HttpContext is not available
            //    HttpContext.Current != null ?
            //    (new HttpContextWrapper(HttpContext.Current) as HttpContextBase) :
            //    (new FakeHttpContext("~/") as HttpContextBase))
            //    .As<HttpContextBase>()
            //    .InstancePerLifetimeScope();
            //builder.Register(c => c.Resolve<HttpContextBase>().Request)
            //    .As<HttpRequestBase>()
            //    .InstancePerLifetimeScope();
            //builder.Register(c => c.Resolve<HttpContextBase>().Response)
            //    .As<HttpResponseBase>()
            //    .InstancePerLifetimeScope();
            //builder.Register(c => c.Resolve<HttpContextBase>().Server)
            //    .As<HttpServerUtilityBase>()
            //    .InstancePerLifetimeScope();
            //builder.Register(c => c.Resolve<HttpContextBase>().Session)
            //    .As<HttpSessionStateBase>()
            //    .InstancePerLifetimeScope();



            //IHttpContextAccessor
            //builder.Register



            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();
            //user agent helper
            builder.RegisterType <UserAgentHelper>().As <IUserAgentHelper>().InstancePerLifetimeScope();


            //controllers
            //builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

            //data layer
            var dataSettingsManager  = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            builder.Register(c => dataSettingsManager.LoadSettings()).As <DataSettings>();
            builder.Register(x => new MongoDBDataProviderManager(x.Resolve <DataSettings>())).As <BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var mongoDBDataProviderManager = new MongoDBDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider = mongoDBDataProviderManager.LoadDataProvider();
                var databaseName = new MongoUrl(dataProviderSettings.DataConnectionString).DatabaseName;
                builder.Register <IMongoClient>(c => new MongoClient(dataProviderSettings.DataConnectionString)).SingleInstance();
                builder.Register(c => new MongoClient(dataProviderSettings.DataConnectionString).GetDatabase(databaseName)).SingleInstance();
                builder.Register <IMongoDBContext>(c => new MongoDBContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MongoClient>().As <IMongoClient>().SingleInstance();
                builder.RegisterType <MongoDBContext>().As <IMongoDBContext>().InstancePerLifetimeScope();
            }

            //MongoDbRepository
            builder.RegisterGeneric(typeof(MongoDBRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();

            //plugins
            builder.RegisterType <PluginFinder>().As <IPluginFinder>().InstancePerLifetimeScope();

            //cache manager
            if (config.RedisCachingEnabled)
            {
                //builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
                //builder.RegisterType<RedisConnectionWrapper>().As<IRedisConnectionWrapper>().SingleInstance();
                //builder.RegisterType<RedisCacheManager>().As<ICacheManager>().SingleInstance();
            }
            else
            {
                //builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("nop_cache_static").SingleInstance();
            }

            if (config.RunOnAzureWebApps)
            {
                //builder.RegisterType<AzureWebAppsMachineNameProvider>().As<IMachineNameProvider>().SingleInstance();
            }
            else
            {
                //builder.RegisterType<DefaultMachineNameProvider>().As<IMachineNameProvider>().SingleInstance();
            }
            //work context
            builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope();
            //store context
            builder.RegisterType <WebStoreContext>().As <IStoreContext>().InstancePerLifetimeScope();

            //services
            builder.RegisterType <BackInStockSubscriptionService>().As <IBackInStockSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerLifetimeScope();
            //builder.RegisterType<CompareProductsService>().As<ICompareProductsService>().InstancePerLifetimeScope();
            builder.RegisterType <RecentlyViewedProductsService>().As <IRecentlyViewedProductsService>().InstancePerLifetimeScope();
            builder.RegisterType <ManufacturerService>().As <IManufacturerService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceFormatter>().As <IPriceFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeFormatter>().As <IProductAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeParser>().As <IProductAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeService>().As <IProductAttributeService>().InstancePerLifetimeScope();

            builder.RegisterType <ProductService>().As <IProductService>().InstancePerLifetimeScope();
            builder.RegisterType <CopyProductService>().As <ICopyProductService>().InstancePerLifetimeScope();

            builder.RegisterType <SpecificationAttributeService>().As <ISpecificationAttributeService>().InstancePerLifetimeScope();

            builder.RegisterType <ProductTemplateService>().As <IProductTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <CategoryTemplateService>().As <ICategoryTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ManufacturerTemplateService>().As <IManufacturerTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <TopicTemplateService>().As <ITopicTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductTagService>().As <IProductTagService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeFormatter>().As <IAddressAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeParser>().As <IAddressAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeService>().As <IAddressAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressService>().As <IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType <AffiliateService>().As <IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorService>().As <IVendorService>().InstancePerLifetimeScope();
            builder.RegisterType <SearchTermService>().As <ISearchTermService>().InstancePerLifetimeScope();
            builder.RegisterType <GenericAttributeService>().As <IGenericAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeFormatter>().As <ICustomerAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeParser>().As <ICustomerAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeService>().As <ICustomerAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerService>().As <ICustomerService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerRegistrationService>().As <ICustomerRegistrationService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReportService>().As <ICustomerReportService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerTagService>().As <ICustomerTagService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionService>().As <ICustomerActionService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionEventService>().As <ICustomerActionEventService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderService>().As <ICustomerReminderService>().InstancePerLifetimeScope();

            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();

            builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope();
            builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceCalculationService>().As <IPriceCalculationService>().InstancePerLifetimeScope();

            builder.RegisterType <GeoLookupService>().As <IGeoLookupService>().InstancePerLifetimeScope();
            builder.RegisterType <CountryService>().As <ICountryService>().InstancePerLifetimeScope();

            builder.RegisterType <CurrencyService>().As <ICurrencyService>().InstancePerLifetimeScope();
            builder.RegisterType <MeasureService>().As <IMeasureService>().InstancePerLifetimeScope();
            builder.RegisterType <StateProvinceService>().As <IStateProvinceService>().InstancePerLifetimeScope();

            builder.RegisterType <StoreService>().As <IStoreService>().InstancePerLifetimeScope();
            builder.RegisterType <StoreMappingService>().As <IStoreMappingService>().InstancePerLifetimeScope();
            builder.RegisterType <DiscountService>().As <IDiscountService>().InstancePerLifetimeScope();


            //pass MemoryCacheManager as cacheManager (cache settings between requests)
            if (config.RedisCachingEnabled)
            {
                builder.RegisterType <SettingService>().As <ISettingService>()
                .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();

                builder.RegisterType <LocalizationService>().As <ILocalizationService>()
                .WithParameter(ResolvedParameter.ForNamed <ICacheManager>("nop_cache_static"))
                .InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <SettingService>().As <ISettingService>().InstancePerLifetimeScope();
                builder.RegisterType <LocalizationService>().As <ILocalizationService>().InstancePerLifetimeScope();
            }

            builder.RegisterSource(new SettingsSource());
            builder.RegisterType <LanguageService>().As <ILanguageService>().InstancePerLifetimeScope();
            builder.RegisterType <DownloadService>().As <IDownloadService>().InstancePerLifetimeScope();

            //picture service
            var useAzureBlobStorage  = !String.IsNullOrEmpty(config.AzureBlobStorageConnectionString);
            var useAmazonBlobStorage = (!String.IsNullOrEmpty(config.AmazonAwsAccessKeyId) && !String.IsNullOrEmpty(config.AmazonAwsSecretAccessKey) && !String.IsNullOrEmpty(config.AmazonBucketName) && !String.IsNullOrEmpty(config.AmazonRegion));

            if (useAzureBlobStorage)
            {
                //Windows Azure BLOB
                //builder.RegisterType<AzurePictureService>().As<IPictureService>().InstancePerLifetimeScope();
            }
            else if (useAmazonBlobStorage)
            {
                //Amazon S3 Simple Storage Service
                //builder.RegisterType<AmazonPictureService>().As<IPictureService>().InstancePerLifetimeScope();
            }
            else
            {
                //standard file system
                builder.RegisterType <PictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }

            builder.RegisterType <MessageTemplateService>().As <IMessageTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <QueuedEmailService>().As <IQueuedEmailService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsLetterSubscriptionService>().As <INewsLetterSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsletterCategoryService>().As <INewsletterCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <CampaignService>().As <ICampaignService>().InstancePerLifetimeScope();
            builder.RegisterType <BannerService>().As <IBannerService>().InstancePerLifetimeScope();
            builder.RegisterType <PopupService>().As <IPopupService>().InstancePerLifetimeScope();
            builder.RegisterType <InteractiveFormService>().As <IInteractiveFormService>().InstancePerLifetimeScope();
            builder.RegisterType <EmailAccountService>().As <IEmailAccountService>().InstancePerLifetimeScope();
            builder.RegisterType <WorkflowMessageService>().As <IWorkflowMessageService>().InstancePerLifetimeScope();
            builder.RegisterType <MessageTokenProvider>().As <IMessageTokenProvider>().InstancePerLifetimeScope();
            builder.RegisterType <Tokenizer>().As <ITokenizer>().InstancePerLifetimeScope();
            builder.RegisterType <EmailSender>().As <IEmailSender>().InstancePerLifetimeScope();

            builder.RegisterType <CheckoutAttributeFormatter>().As <ICheckoutAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <CheckoutAttributeParser>().As <ICheckoutAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <CheckoutAttributeService>().As <ICheckoutAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <GiftCardService>().As <IGiftCardService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderService>().As <IOrderService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderReportService>().As <IOrderReportService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderProcessingService>().As <IOrderProcessingService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderTotalCalculationService>().As <IOrderTotalCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType <ReturnRequestService>().As <IReturnRequestService>().InstancePerLifetimeScope();
            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();
            builder.RegisterType <ShoppingCartService>().As <IShoppingCartService>().InstancePerLifetimeScope();
            builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType </*FormsAuthenticationService*/ CookieAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <UrlRecordService>().As <IUrlRecordService>().InstancePerLifetimeScope();
            builder.RegisterType <ShipmentService>().As <IShipmentService>().InstancePerLifetimeScope();
            builder.RegisterType <ShippingService>().As <IShippingService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxCategoryService>().As <ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxService>().As <ITaxService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxCategoryService>().As <ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();
            builder.RegisterType <ContactUsService>().As <IContactUsService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActivityService>().As <ICustomerActivityService>().InstancePerLifetimeScope();
            builder.RegisterType <ActivityKeywordsProvider>().As <IActivityKeywordsProvider>().InstancePerLifetimeScope();

            bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();

            if (!databaseInstalled)
            {
                //installation service
                builder.RegisterType <CodeFirstInstallationService>().As <IInstallationService>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <UpgradeService>().As <IUpgradeService>().InstancePerLifetimeScope();
            }

            builder.RegisterType <ForumService>().As <IForumService>().InstancePerLifetimeScope();
            builder.RegisterType <PollService>().As <IPollService>().InstancePerLifetimeScope();
            builder.RegisterType <BlogService>().As <IBlogService>().InstancePerLifetimeScope();
            builder.RegisterType <WidgetService>().As <IWidgetService>().InstancePerLifetimeScope();
            builder.RegisterType <TopicService>().As <ITopicService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsService>().As <INewsService>().InstancePerLifetimeScope();
            builder.RegisterType <DateTimeHelper>().As <IDateTimeHelper>().InstancePerLifetimeScope();
            builder.RegisterType <SitemapGenerator>().As <ISitemapGenerator>().InstancePerLifetimeScope();
            builder.RegisterType <PageHeadBuilder>().As <IPageHeadBuilder>().InstancePerLifetimeScope();
            builder.RegisterType <ScheduleTaskService>().As <IScheduleTaskService>().InstancePerLifetimeScope();
            builder.RegisterType <ExportManager>().As <IExportManager>().InstancePerLifetimeScope();
            builder.RegisterType <ImportManager>().As <IImportManager>().InstancePerLifetimeScope();
            builder.RegisterType <PdfService>().As <IPdfService>().InstancePerLifetimeScope();
            builder.RegisterType <ThemeProvider>().As <IThemeProvider>().InstancePerLifetimeScope();

            //2017_05_17 added
            builder.RegisterType <ThemeContext>().As <IThemeContext>().InstancePerLifetimeScope();


            builder.RegisterType <ThemeContext>().As <IThemeContext>().InstancePerLifetimeScope();
            builder.RegisterType <ExternalAuthorizer>().As <IExternalAuthorizer>().InstancePerLifetimeScope();
            builder.RegisterType <OpenAuthenticationService>().As <IOpenAuthenticationService>().InstancePerLifetimeScope();
            //builder.RegisterType<GoogleAnalyticsService>().As<IGoogleAnalyticsService>().InstancePerLifetimeScope();



            Debug.Write("");
            //VERY strange
            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();



            //Register event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer <>)).ToList();

            //foreach (var consumer in consumers)
            //{
            //    builder.RegisterType(consumer)
            //        .As(consumer.FindInterfaces((type, criteria) =>
            //        {
            //            var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
            //            return isMatch;
            //        }, typeof(IConsumer<>)))
            //        .InstancePerLifetimeScope();
            //}
            builder.RegisterType <EventPublisher>().As <IEventPublisher>().SingleInstance();
            builder.RegisterType <SubscriptionService>().As <ISubscriptionService>().SingleInstance();
        }
 public CategoryRepository(MongoUrl mongoUrl, IMapper mapper)
     : base(mongoUrl) => _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
예제 #14
0
 public DirectConnector(
     MongoUrl url
 )
 {
     this.url = url;
 }
 public ReplicaSetConnector(
     MongoUrl url
 )
 {
     this.url = url;
 }
예제 #16
0
        public void constructor_with_string_and_bool_should_initialize_instance(string url, bool isResolved)
        {
            var result = new MongoUrl(url, isResolved);

            result.IsResolved.Should().Be(isResolved);
        }
예제 #17
0
 /// <summary>
 ///     Creates and returns an IMongoCollection from the specified type and url.
 /// </summary>
 /// <typeparam name="T">The type to get the collection of.</typeparam>
 /// <param name="url">The url to use to get the collection from.</param>
 /// <returns>Returns an IMongoCollection from the specified type and url.</returns>
 public static IMongoCollection <T> GetCollectionFromUrl <T>(MongoUrl url)
     where T : IEntity <U>
 {
     return(GetCollectionFromUrl <T>(url, GetCollectionName <T>()));
 }
예제 #18
0
        protected override IRepository <T> CreateRepository <T>(string collectionName)
        {
            var url = new MongoUrl(_mongourl);

            return(new MongoRepository <T>(url, collectionName));
        }
예제 #19
0
        protected override IRepository <T, K> CreateRepository <T, K>()
        {
            var url = new MongoUrl(_mongourl);

            return(new MongoRepository <T, K>(url));
        }
예제 #20
0
 public MongoConnection(string connectionString)
     : this(connectionString, connectionString == null ? null : MongoUrl.Create(connectionString).DatabaseName)
 {
 }
 public BillingEventRepository(MongoUrl url) : base(url)
 {
 }
예제 #22
0
 /// <summary>
 /// Creates and returns a MongoDatabase from the specified url.
 /// </summary>
 /// <param name="url">The url to use to get the database from.</param>
 /// <returns>Returns a MongoDatabase from the specified url.</returns>
 private static MongoDatabaseBase GetDatabaseFromUrl(MongoUrl url)
 {
     return((MongoDatabaseBase) new MongoClient(url).GetDatabase(url.DatabaseName));
 }
예제 #23
0
        /// <summary>
        /// Register services and interfaces
        /// </summary>
        /// <param name="builder">Container builder</param>
        /// <param name="typeFinder">Type finder</param>
        /// <param name="config">Config</param>
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, GrandConfig config)
        {
            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

            //powered by
            builder.RegisterType <PoweredByMiddlewareOptions>().As <IPoweredByMiddlewareOptions>().SingleInstance();

            //data layer
            var dataSettingsManager  = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            builder.Register(c => dataSettingsManager.LoadSettings()).As <DataSettings>();
            builder.Register(x => new MongoDBDataProviderManager(x.Resolve <DataSettings>())).As <BaseDataProviderManager>().InstancePerDependency();
            builder.Register(x => x.Resolve <BaseDataProviderManager>().LoadDataProvider()).As <IDataProvider>().InstancePerDependency();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                var connectionString = dataProviderSettings.DataConnectionString;
                var databaseName     = new MongoUrl(connectionString).DatabaseName;
                builder.Register(c => new MongoClient(connectionString).GetDatabase(databaseName)).SingleInstance();
                builder.Register <IMongoDBContext>(c => new MongoDBContext(connectionString)).InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <MongoDBContext>().As <IMongoDBContext>().InstancePerLifetimeScope();
            }

            //MongoDbRepository
            builder.RegisterGeneric(typeof(MongoDBRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();

            //plugins
            builder.RegisterType <PluginFinder>().As <IPluginFinder>().InstancePerLifetimeScope();

            //cache manager
            builder.RegisterType <PerRequestCacheManager>().InstancePerLifetimeScope();
            builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().SingleInstance();

            if (config.RedisCachingEnabled)
            {
                builder.RegisterType <DistributedRedisCache>().As <ICacheManager>().SingleInstance();
                builder.RegisterType <DistributedRedisCacheExtended>().As <IDistributedRedisCacheExtended>().SingleInstance();
            }
            else
            {
                builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().SingleInstance();
            }

            if (config.RunOnAzureWebApps)
            {
                builder.RegisterType <AzureWebAppsMachineNameProvider>().As <IMachineNameProvider>().SingleInstance();
            }
            else
            {
                builder.RegisterType <DefaultMachineNameProvider>().As <IMachineNameProvider>().SingleInstance();
            }
            //work context
            builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope();
            //store context
            builder.RegisterType <WebStoreContext>().As <IStoreContext>().InstancePerLifetimeScope();

            builder.RegisterType <SettingService>().As <ISettingService>().InstancePerLifetimeScope();
            builder.RegisterType <LocalizationService>().As <ILocalizationService>().InstancePerLifetimeScope();

            //services
            builder.RegisterType <BackInStockSubscriptionService>().As <IBackInStockSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <CompareProductsService>().As <ICompareProductsService>().InstancePerLifetimeScope();
            builder.RegisterType <RecentlyViewedProductsService>().As <IRecentlyViewedProductsService>().InstancePerLifetimeScope();
            builder.RegisterType <ManufacturerService>().As <IManufacturerService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceFormatter>().As <IPriceFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeFormatter>().As <IProductAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeParser>().As <IProductAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <ProductAttributeService>().As <IProductAttributeService>().InstancePerLifetimeScope();

            builder.RegisterType <ProductService>().As <IProductService>().InstancePerLifetimeScope();
            builder.RegisterType <CopyProductService>().As <ICopyProductService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductReservationService>().As <IProductReservationService>().InstancePerLifetimeScope();
            builder.RegisterType <AuctionService>().As <IAuctionService>().InstancePerLifetimeScope();

            builder.RegisterType <SpecificationAttributeService>().As <ISpecificationAttributeService>().InstancePerLifetimeScope();

            builder.RegisterType <ProductTemplateService>().As <IProductTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <CategoryTemplateService>().As <ICategoryTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ManufacturerTemplateService>().As <IManufacturerTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <TopicTemplateService>().As <ITopicTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductTagService>().As <IProductTagService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeFormatter>().As <IAddressAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeParser>().As <IAddressAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <AddressAttributeService>().As <IAddressAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <AddressService>().As <IAddressService>().InstancePerLifetimeScope();
            builder.RegisterType <AffiliateService>().As <IAffiliateService>().InstancePerLifetimeScope();
            builder.RegisterType <VendorService>().As <IVendorService>().InstancePerLifetimeScope();
            builder.RegisterType <SearchTermService>().As <ISearchTermService>().InstancePerLifetimeScope();
            builder.RegisterType <GenericAttributeService>().As <IGenericAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeFormatter>().As <ICustomerAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeParser>().As <ICustomerAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerAttributeService>().As <ICustomerAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerService>().As <ICustomerService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerRegistrationService>().As <ICustomerRegistrationService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReportService>().As <ICustomerReportService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerTagService>().As <ICustomerTagService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionService>().As <ICustomerActionService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActionEventService>().As <ICustomerActionEventService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderService>().As <ICustomerReminderService>().InstancePerLifetimeScope();
            builder.RegisterType <UserApiService>().As <IUserApiService>().InstancePerLifetimeScope();

            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();

            builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope();
            builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope();
            builder.RegisterType <PriceCalculationService>().As <IPriceCalculationService>().InstancePerLifetimeScope();

            builder.RegisterType <GeoLookupService>().As <IGeoLookupService>().InstancePerLifetimeScope();
            builder.RegisterType <CountryService>().As <ICountryService>().InstancePerLifetimeScope();

            builder.RegisterType <CurrencyService>().As <ICurrencyService>().InstancePerLifetimeScope();
            builder.RegisterType <MeasureService>().As <IMeasureService>().InstancePerLifetimeScope();
            builder.RegisterType <StateProvinceService>().As <IStateProvinceService>().InstancePerLifetimeScope();

            builder.RegisterType <StoreService>().As <IStoreService>().InstancePerLifetimeScope();
            builder.RegisterType <StoreMappingService>().As <IStoreMappingService>().InstancePerLifetimeScope();
            builder.RegisterType <DiscountService>().As <IDiscountService>().InstancePerLifetimeScope();


            builder.RegisterType <LanguageService>().As <ILanguageService>().InstancePerLifetimeScope();
            builder.RegisterType <DownloadService>().As <IDownloadService>().InstancePerLifetimeScope();

            var provider = new FileExtensionContentTypeProvider();

            builder.RegisterType <MimeMappingService>().As <IMimeMappingService>()
            .WithParameter(new TypedParameter(typeof(FileExtensionContentTypeProvider), provider))
            .InstancePerLifetimeScope();

            //picture service
            var useAzureBlobStorage  = !String.IsNullOrEmpty(config.AzureBlobStorageConnectionString);
            var useAmazonBlobStorage = (!String.IsNullOrEmpty(config.AmazonAwsAccessKeyId) && !String.IsNullOrEmpty(config.AmazonAwsSecretAccessKey) && !String.IsNullOrEmpty(config.AmazonBucketName) && !String.IsNullOrEmpty(config.AmazonRegion));

            if (useAzureBlobStorage)
            {
                //Windows Azure BLOB
                builder.RegisterType <AzurePictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }
            else if (useAmazonBlobStorage)
            {
                //Amazon S3 Simple Storage Service
                builder.RegisterType <AmazonPictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }
            else
            {
                //standard file system
                builder.RegisterType <PictureService>().As <IPictureService>().InstancePerLifetimeScope();
            }

            builder.RegisterType <MessageTemplateService>().As <IMessageTemplateService>().InstancePerLifetimeScope();
            builder.RegisterType <QueuedEmailService>().As <IQueuedEmailService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsLetterSubscriptionService>().As <INewsLetterSubscriptionService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsletterCategoryService>().As <INewsletterCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <CampaignService>().As <ICampaignService>().InstancePerLifetimeScope();
            builder.RegisterType <BannerService>().As <IBannerService>().InstancePerLifetimeScope();
            builder.RegisterType <PopupService>().As <IPopupService>().InstancePerLifetimeScope();
            builder.RegisterType <InteractiveFormService>().As <IInteractiveFormService>().InstancePerLifetimeScope();
            builder.RegisterType <EmailAccountService>().As <IEmailAccountService>().InstancePerLifetimeScope();
            builder.RegisterType <WorkflowMessageService>().As <IWorkflowMessageService>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeFormatter>().As <IContactAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeParser>().As <IContactAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <ContactAttributeService>().As <IContactAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <MessageTokenProvider>().As <IMessageTokenProvider>().InstancePerLifetimeScope();
            builder.RegisterType <Tokenizer>().As <ITokenizer>().InstancePerLifetimeScope();
            builder.RegisterType <EmailSender>().As <IEmailSender>().InstancePerLifetimeScope();
            builder.RegisterType <HistoryService>().As <IHistoryService>().InstancePerLifetimeScope();
            builder.RegisterType <CheckoutAttributeFormatter>().As <ICheckoutAttributeFormatter>().InstancePerLifetimeScope();
            builder.RegisterType <CheckoutAttributeParser>().As <ICheckoutAttributeParser>().InstancePerLifetimeScope();
            builder.RegisterType <CheckoutAttributeService>().As <ICheckoutAttributeService>().InstancePerLifetimeScope();
            builder.RegisterType <GiftCardService>().As <IGiftCardService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderService>().As <IOrderService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderReportService>().As <IOrderReportService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderProcessingService>().As <IOrderProcessingService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderTotalCalculationService>().As <IOrderTotalCalculationService>().InstancePerLifetimeScope();
            builder.RegisterType <ReturnRequestService>().As <IReturnRequestService>().InstancePerLifetimeScope();
            builder.RegisterType <RewardPointsService>().As <IRewardPointsService>().InstancePerLifetimeScope();
            builder.RegisterType <ShoppingCartService>().As <IShoppingCartService>().InstancePerLifetimeScope();
            builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType <CookieAuthenticationService>().As <IGrandAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <ApiAuthenticationService>().As <IApiAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <UrlRecordService>().As <IUrlRecordService>().InstancePerLifetimeScope();
            builder.RegisterType <ShipmentService>().As <IShipmentService>().InstancePerLifetimeScope();
            builder.RegisterType <ShippingService>().As <IShippingService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxCategoryService>().As <ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxService>().As <ITaxService>().InstancePerLifetimeScope();
            builder.RegisterType <TaxCategoryService>().As <ITaxCategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();
            builder.RegisterType <ContactUsService>().As <IContactUsService>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerActivityService>().As <ICustomerActivityService>().InstancePerLifetimeScope();
            builder.RegisterType <ActivityKeywordsProvider>().As <IActivityKeywordsProvider>().InstancePerLifetimeScope();

            bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled();

            if (!databaseInstalled)
            {
                //installation service
                builder.RegisterType <CodeFirstInstallationService>().As <IInstallationService>().InstancePerLifetimeScope();
            }
            else
            {
                builder.RegisterType <UpgradeService>().As <IUpgradeService>().InstancePerLifetimeScope();
            }

            builder.RegisterType <ForumService>().As <IForumService>().InstancePerLifetimeScope();
            builder.RegisterType <KnowledgebaseService>().As <IKnowledgebaseService>().InstancePerLifetimeScope();
            builder.RegisterType <PushNotificationsService>().As <IPushNotificationsService>().InstancePerLifetimeScope();
            builder.RegisterType <PollService>().As <IPollService>().InstancePerLifetimeScope();
            builder.RegisterType <BlogService>().As <IBlogService>().InstancePerLifetimeScope();
            builder.RegisterType <WidgetService>().As <IWidgetService>().InstancePerLifetimeScope();
            builder.RegisterType <TopicService>().As <ITopicService>().InstancePerLifetimeScope();
            builder.RegisterType <NewsService>().As <INewsService>().InstancePerLifetimeScope();
            builder.RegisterType <DateTimeHelper>().As <IDateTimeHelper>().InstancePerLifetimeScope();
            builder.RegisterType <SitemapGenerator>().As <ISitemapGenerator>().InstancePerLifetimeScope();
            builder.RegisterType <PageHeadBuilder>().As <IPageHeadBuilder>().InstancePerLifetimeScope();
            builder.RegisterType <ScheduleTaskService>().As <IScheduleTaskService>().InstancePerLifetimeScope();
            builder.RegisterType <ExportManager>().As <IExportManager>().InstancePerLifetimeScope();
            builder.RegisterType <ImportManager>().As <IImportManager>().InstancePerLifetimeScope();
            builder.RegisterType <PdfService>().As <IPdfService>().InstancePerLifetimeScope();
            builder.RegisterType <ThemeProvider>().As <IThemeProvider>().InstancePerLifetimeScope();
            builder.RegisterType <ThemeContext>().As <IThemeContext>().InstancePerLifetimeScope();
            builder.RegisterType <ExternalAuthenticationService>().As <IExternalAuthenticationService>().InstancePerLifetimeScope();
            builder.RegisterType <GoogleAnalyticsService>().As <IGoogleAnalyticsService>().InstancePerLifetimeScope();
            builder.RegisterType <DocumentTypeService>().As <IDocumentTypeService>().InstancePerLifetimeScope();
            builder.RegisterType <DocumentService>().As <IDocumentService>().InstancePerLifetimeScope();

            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();

            var validators = typeFinder.FindClassesOfType(typeof(IValidator)).ToList();

            foreach (var validator in validators)
            {
                builder.RegisterType(validator);
            }

            //validator consumers
            var validatorconsumers = typeFinder.FindClassesOfType(typeof(IValidatorConsumer <>)).ToList();

            foreach (var consumer in validatorconsumers)
            {
                builder.RegisterType(consumer)
                .As(consumer.GetTypeInfo().FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.GetTypeInfo().IsGenericType&& ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(IValidatorConsumer <>)))
                .InstancePerLifetimeScope();
            }

            builder.RegisterType <ResourceManager>().As <IResourceManager>().InstancePerLifetimeScope();

            //Register task
            builder.RegisterType <QueuedMessagesSendScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <ClearCacheScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <ClearLogScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderAbandonedCartScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderBirthdayScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderCompletedOrderScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderLastActivityScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderLastPurchaseScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderRegisteredCustomerScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <CustomerReminderUnpaidOrderScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <DeleteGuestsScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <UpdateExchangeRateScheduleTask>().As <IScheduleTask>().InstancePerLifetimeScope();
            builder.RegisterType <EndAuctionsTask>().As <IScheduleTask>().InstancePerLifetimeScope();
        }
예제 #24
0
        private Dictionary <string, MongoUrl> getCacheReference(MongoUrl target)
        {
            var fieldInfo = typeof(MongoUrl).GetField("__cache", BindingFlags.Static | BindingFlags.GetField | BindingFlags.NonPublic);

            return(fieldInfo.GetValue(target) as Dictionary <string, MongoUrl>);
        }
예제 #25
0
        public MongoDbContext(IOptions <MongoDbOptions> options)
        {
            var connectionString = options.Value.ConnectionString;
            var mongoClient      = new MongoClient(connectionString);
            var databaseName     = options.Value.DatabaseName is not null and not "" ? options.Value.DatabaseName : MongoUrl.Create(connectionString).DatabaseName;

            if (databaseName == null)
            {
                throw new Exception("Please specify a database name, either via the connection string or via the DatabaseName setting.");
            }

            MongoDatabase = mongoClient.GetDatabase(databaseName);
        }
예제 #26
0
 public InviteRepository(MongoUrl mongoUrl)
     : base(mongoUrl)
 {
 }
예제 #27
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            string connectionString = "";

            if (model.MongoDBConnectionInfo)
            {
                if (String.IsNullOrEmpty(model.DatabaseConnectionString))
                {
                    ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                }
                else
                {
                    connectionString = model.DatabaseConnectionString;
                }
            }
            else
            {
                if (String.IsNullOrEmpty(model.MongoDBDatabaseName))
                {
                    ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                }
                if (String.IsNullOrEmpty(model.MongoDBServerName))
                {
                    ModelState.AddModelError("", _locService.GetResource("MongoDBServerNameRequired"));
                }
                string userNameandPassword = "";
                if (!(String.IsNullOrEmpty(model.MongoDBUsername)))
                {
                    userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";
                }

                connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;
            }

            if (!string.IsNullOrEmpty(connectionString))
            {
                try
                {
                    var client       = new MongoClient(connectionString);
                    var databaseName = new MongoUrl(connectionString).DatabaseName;
                    var database     = client.GetDatabase(databaseName);
                    database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait();

                    var filter = new BsonDocument("name", "GrandNodeVersion");
                    var found  = database.ListCollectionsAsync(new ListCollectionsOptions {
                        Filter = filter
                    }).Result;

                    if (found.Any())
                    {
                        ModelState.AddModelError("", _locService.GetResource("AlreadyInstalled"));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
            }

            var webHelper = _serviceProvider.GetRequiredService <IWebHelper>();

            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                }
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var settings = new DataSettings
                    {
                        DataProvider         = "mongodb",
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    var dataProviderInstance = _serviceProvider.GetRequiredService <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    var dataSettingsManager  = new DataSettingsManager();
                    var dataProviderSettings = dataSettingsManager.LoadSettings(reloadSettings: true);

                    var installationService = _serviceProvider.GetRequiredService <IInstallationService>();
                    await installationService.InstallData(model.AdminEmail, model.AdminPassword, model.Collation, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = _serviceProvider.GetRequiredService <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(LoadPluginsMode.All)
                                       .ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();

                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                                                           new List <string>() :
                                                           _config.PluginsIgnoredDuringInstallation
                                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();

                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                        {
                            continue;
                        }

                        try
                        {
                            await plugin.Install();
                        }
                        catch (Exception ex)
                        {
                            var _logger = _serviceProvider.GetRequiredService <ILogger>();
                            await _logger.InsertLog(Core.Domain.Logging.LogLevel.Error, "Error during installing plugin " + plugin.PluginDescriptor.SystemName,
                                                    ex.Message + " " + ex.InnerException?.Message);
                        }
                    }

                    //register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        await _serviceProvider.GetRequiredService <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    if (Core.OperatingSystem.IsWindows())
                    {
                        webHelper.RestartAppDomain();
                        //Redirect to home page
                        return(RedirectToRoute("HomePage"));
                    }
                    else
                    {
                        return(View(new InstallModel()
                        {
                            Installed = true
                        }));
                    }
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();
                    await _cacheManager.Clear();

                    System.IO.File.Delete(CommonHelper.MapPath("~/App_Data/Settings.txt"));

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message + " " + exception.InnerException?.Message));
                }
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            //prepare collation list
            foreach (var col in _locService.GetAvailableCollations())
            {
                model.AvailableCollation.Add(new SelectListItem
                {
                    Value    = col.Value,
                    Text     = col.Name,
                    Selected = _locService.GetCurrentLanguage().Code == col.Value,
                });
            }

            return(View(model));
        }
예제 #28
0
 protected MongoRepository(MongoUrl mongoUrl)
     : base(mongoUrl)
 {
 }
예제 #29
0
 public UserRepository(MongoUrl mongoUrl)
     : base(MongoFactory.GetDatabaseFromMongoUrl(mongoUrl))
 {
 }
예제 #30
0
#pragma warning disable CS0618 // Type or member is obsolete
        public static void _connectionModeSwitch(this MongoUrl url, ConnectionModeSwitch connectionModeSwitch)
#pragma warning restore CS0618 // Type or member is obsolete
        {
            Reflector.SetFieldValue(url, nameof(_connectionModeSwitch), connectionModeSwitch);
        }
예제 #31
0
        public override bool Connect()
        {
            try
            {
                ///
                /// ConnectionString format
                /// "mongodb://*****:*****@localhost/DB"
                ///
                if (Db.ConnectionString != null && !string.IsNullOrEmpty(Db.ConnectionString))
                {
                    var connectionString = Db.ConnectionStringCalculated.ToString();
                    DbName = MongoUrl.Create(Db.ConnectionStringCalculated.ToString()).DatabaseName;
                    if (DbName == null)
                    {
                        return(false);
                    }
                    mMongoClient = new MongoClient(connectionString);
                }
                else
                {
                    ///
                    /// Host format
                    /// "mongodb://HostOrIP:27017/DBName"
                    ///
                    string[] HostPortDB = Db.TNSCalculated.Split('/');
                    string[] HostPort   = HostPortDB[0].Split(':');
                    //need to get db name

                    MongoCredential     mongoCredential     = null;
                    MongoClientSettings mongoClientSettings = null;
                    if (HostPort.Length == 2 && HostPortDB.Length == 2)
                    {
                        if (string.IsNullOrEmpty(HostPortDB[HostPortDB.Length - 1]))
                        {
                            Reporter.ToLog(eLogLevel.ERROR, "Database is not mentioned in the TNS/Host.");
                            return(false);
                        }

                        if (string.IsNullOrEmpty(Db.Pass) && string.IsNullOrEmpty(Db.User))
                        {
                            mongoClientSettings = new MongoClientSettings
                            {
                                Server = new MongoServerAddress(HostPort[0], Convert.ToInt32(HostPort[1]))
                            };
                        }
                        else
                        {
                            bool   res          = false;
                            String deCryptValue = EncryptionHandler.DecryptString(Db.PassCalculated.ToString(), ref res, false);
                            if (res == true)
                            {
                                mongoCredential = MongoCredential.CreateCredential(HostPortDB[HostPortDB.Length - 1], Db.UserCalculated, deCryptValue);
                            }
                            else
                            {
                                mongoCredential = MongoCredential.CreateCredential(HostPortDB[HostPortDB.Length - 1], Db.UserCalculated, Db.PassCalculated.ToString());
                            }
                            mongoClientSettings = new MongoClientSettings
                            {
                                Server = new MongoServerAddress(HostPort[0], Convert.ToInt32(HostPort[1])),
                                //UseSsl = true,
                                Credentials = new[] { mongoCredential }
                            };
                        }
                        DbName       = HostPortDB[HostPortDB.Length - 1];
                        mMongoClient = new MongoClient(mongoClientSettings);
                    }
                    else
                    {
                        return(false);
                    }
                }
                //check dbname is present in the dblist
                if (GetDatabaseList().Contains(DbName))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Reporter.ToLog(eLogLevel.ERROR, "Failed to connect to Mongo DB", e);
                return(false);
            }
        }
 public MongoDbHealthCheck(string connectionString, string databaseName = default)
     : this(MongoClientSettings.FromUrl(MongoUrl.Create(connectionString)), databaseName)
 {
 }
예제 #33
0
        /// <summary>
        ///     Creates and returns a MongoDatabase from the specified url.
        /// </summary>
        /// <param name="url">The url to use to get the database from.</param>
        /// <returns>Returns a MongoDatabase from the specified url.</returns>
        private static IMongoDatabase GetDatabaseFromUrl(MongoUrl url)
        {
            var client = new MongoClient(url);

            return(client.GetDatabase(url.DatabaseName)); // WriteConcern defaulted to Acknowledged
        }
예제 #34
0
        /// <summary>
        /// 添加 MongoDB 拓展
        /// </summary>
        /// <param name="services"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static IServiceCollection AddMongoDB(this IServiceCollection services, MongoUrl url)
        {
            // 创建数据库连接对象
            services.AddScoped(u =>
            {
                return(new MongoClient(url));
            });

            // 注册 MongoDB 仓储
            services.AddScoped <IMongoDBRepository, MongoDBRepository>();

            return(services);
        }
예제 #35
0
 /// <summary>
 ///     Creates and returns an IMongoCollection from the specified type and url.
 /// </summary>
 /// <typeparam name="T">The type to get the collection of.</typeparam>
 /// <param name="url">The url to use to get the collection from.</param>
 /// <param name="collectionName">The name of the collection to use.</param>
 /// <returns>Returns an IMongoCollection from the specified type and url.</returns>
 public static IMongoCollection <T> GetCollectionFromUrl <T>(MongoUrl url, string collectionName)
     where T : IEntity <U>
 {
     return(GetDatabaseFromUrl(url)
            .GetCollection <T>(collectionName));
 }
예제 #36
0
 public TemplateRepository(MongoUrl mongoUrl)
     : base(MongoFactory.GetDatabaseFromMongoUrl(mongoUrl))
 {
 }
        public void TestFromUrlWithMongoDBX509()
        {
            var url = new MongoUrl("mongodb://username@localhost/?authMechanism=MONGODB-X509");
            var settings = MongoClientSettings.FromUrl(url);

            var credential = settings.Credentials.Single();
            Assert.AreEqual("MONGODB-X509", credential.Mechanism);
            Assert.AreEqual("username", credential.Username);
            Assert.IsInstanceOf<ExternalEvidence>(credential.Evidence);
        }
예제 #38
0
 /// <summary>
 /// Initializes a new instance of the MongoClient class.
 /// </summary>
 /// <param name="url">The URL.</param>
 public MongoClient(MongoUrl url)
     : this(MongoClientSettings.FromUrl(url))
 {
 }