public void Initialize()
        {
            MigrationResolver.Current = new MigrationResolver(
                Mock.Of <ILogger>(),
                () => new List <Type>
            {
                typeof(AlterUserTableMigrationStub),
                typeof(Dummy),
                typeof(SixZeroMigration1),
                typeof(SixZeroMigration2),
                typeof(FourElevenMigration),
                typeof(FiveZeroMigration)
            });

            var sqlSyntax = new SqlCeSyntaxProvider();

            //This is needed because the Migration resolver is creating migration instances with their full ctors
            ApplicationContext.EnsureContext(
                new ApplicationContext(
                    new DatabaseContext(Mock.Of <IScopeProviderInternal>(), Mock.Of <ILogger>(), sqlSyntax, "test"),
                    new ServiceContext(),
                    CacheHelper.CreateDisabledCacheHelper(),
                    new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())),
                true);

            //This is needed because the Migration resolver is creating the migration instances with their full ctors
            LoggerResolver.Current = new LoggerResolver(Mock.Of <ILogger>())
            {
                CanResolveBeforeFrozen = true
            };

            Resolution.Freeze();
        }
示例#2
0
        private void UmbracoVersionSpecificCreate()
        {
            var logger          = Logger.CreateWithDefaultLog4NetConfiguration();
            var syntaxProvider  = new SqlCeSyntaxProvider();
            var cacheHelper     = new CacheHelper();
            var database        = new UmbracoDatabase(ConnectionString, new SqlCeProviderFactory(), logger);
            var databaseFactory = Mock.Of <IDatabaseFactory>(f => f.CreateDatabase() == database);
            var databaseContext = new DatabaseContext(
                databaseFactory, logger,
                new SqlSyntaxProviders(new [] { syntaxProvider })
                );
            var migrationEntryService = new MigrationEntryService(
                new PetaPocoUnitOfWorkProvider(databaseFactory),
                new RepositoryFactory(cacheHelper, logger, syntaxProvider, new UmbracoSettingsSection()),
                logger,
                Mock.Of <IEventMessagesFactory>()
                );
            var serviceContext     = new ServiceContext(migrationEntryService: migrationEntryService);
            var applicationContext = new ApplicationContext(
                databaseContext, serviceContext, cacheHelper,
                new ProfilingLogger(logger, Mock.Of <IProfiler>())
                );

            var helper = new DatabaseSchemaHelper(databaseContext.Database, logger, syntaxProvider);

            helper.CreateDatabaseSchema(false, applicationContext);
        }
示例#3
0
        /// <summary>
        /// Gets an UmbracoDatabase.
        /// </summary>
        /// <param name="logger">A logger.</param>
        /// <returns>An UmbracoDatabase.</returns>
        /// <remarks>This is just a void database that has no actual database but pretends to have an open connection
        /// that can begin a transaction.</remarks>
        public UmbracoDatabase GetUmbracoSqlCeDatabase(ILogger logger)
        {
            var syntax     = new SqlCeSyntaxProvider();
            var connection = GetDbConnection();
            var sqlContext = new SqlContext(syntax, DatabaseType.SQLCe, Mock.Of <IPocoDataFactory>());

            return(new UmbracoDatabase(connection, sqlContext, logger));
        }
示例#4
0
        /// <summary>
        /// Gets an UmbracoDatabase.
        /// </summary>
        /// <param name="logger">A logger.</param>
        /// <returns>An UmbracoDatabase.</returns>
        /// <remarks>This is just a void database that has no actual database but pretends to have an open connection
        /// that can begin a transaction.</remarks>
        public UmbracoDatabase GetUmbracoSqlCeDatabase(ILogger <UmbracoDatabase> logger)
        {
            var syntax     = new SqlCeSyntaxProvider(Options.Create(new GlobalSettings()));
            var connection = GetDbConnection();
            var sqlContext = new SqlContext(syntax, DatabaseType.SQLCe, Mock.Of <IPocoDataFactory>());

            return(new UmbracoDatabase(connection, sqlContext, logger, TestHelper.BulkSqlInsertProvider));
        }
 public void Setup()
 {
     // create the database factory and database context
     _sqlCeSyntaxProvider = new SqlCeSyntaxProvider();
     _sqlSyntaxProviders  = new[] { (ISqlSyntaxProvider)_sqlCeSyntaxProvider };
     _logger          = Mock.Of <ILogger>();
     _databaseFactory = new UmbracoDatabaseFactory(_logger, new Lazy <IMapperCollection>(() => Mock.Of <IMapperCollection>()));
 }
        protected Lazy <ISqlContext> MockSqlContext()
        {
            var sqlContext = Mock.Of <ISqlContext>();
            var syntax     = new SqlCeSyntaxProvider();

            Mock.Get(sqlContext).Setup(x => x.SqlSyntax).Returns(syntax);
            return(new Lazy <ISqlContext>(() => sqlContext));
        }
示例#7
0
        protected Lazy <ISqlContext> MockSqlContext()
        {
            var sqlContext = Mock.Of <ISqlContext>();
            var syntax     = new SqlCeSyntaxProvider(Options.Create(new GlobalSettings()));

            Mock.Get(sqlContext).Setup(x => x.SqlSyntax).Returns(syntax);
            return(new Lazy <ISqlContext>(() => sqlContext));
        }
        public virtual void Initialize()
        {
            // Disable medium trust
            var transform = TransformWebConfig("Release");

            var assemblyPath = TestHelper.CurrentAssemblyDirectory;

            assemblyPath = Path.Combine(assemblyPath, @"..\..\..\Umbraco.Web.UI\");
            var webUiPath = Path.GetFullPath(new Uri(assemblyPath).LocalPath);

            var installedPackagesConfig = string.Format("{0}App_Data\\packages\\installed\\installedPackages.config", webUiPath);

            if (File.Exists(installedPackagesConfig))
            {
                File.Delete(installedPackagesConfig);
            }

            var databaseDataPath = string.Format(@"{0}\App_Data\Umbraco.sdf", webUiPath);
            var connectionString = string.Format(@"Data Source={0}", databaseDataPath);

            //Create the Sql CE database
            using (var engine = new SqlCeEngine(connectionString))
            {
                if (File.Exists(databaseDataPath) == false)
                {
                    engine.CreateDatabase();
                }
            }

            var syntaxProvider = new SqlCeSyntaxProvider();

            SqlSyntaxContext.SqlSyntaxProvider = syntaxProvider;

            _database = new UmbracoDatabase(connectionString, Constants.DatabaseProviders.SqlCe, Mock.Of <ILogger>());

            // First remove anything in the database
            var creation = new DatabaseSchemaCreation(_database, Mock.Of <ILogger>(), syntaxProvider);

            creation.UninstallDatabaseSchema();

            // Then populate it with fresh data
            _database.CreateDatabaseSchema(false);

            _database.Execute("UPDATE umbracoUser SET userName = '******', userPassword = '******', userEmail = 'none' WHERE id = 0"); // password: test

            // Recycle app pool so the new user can log in
            //var webConfigFilePath = string.Format(@"{0}\web.config", webUiPath);
            //File.SetLastWriteTime(webConfigFilePath, DateTime.Now);

            // Disable medium trust
            transform = TransformWebConfig("Release");

            Driver              = new FirefoxDriver();
            BaseUrl             = "http://localhost:61639/";
            _verificationErrors = new StringBuilder();
        }
        public void Setup()
        {
            var logger = new DebugDiagnosticsLogger();
            var path   = TestHelper.CurrentAssemblyDirectory;

            _sqlCeSyntax     = new SqlCeSyntaxProvider();
            _sqlServerSyntax = new SqlServerSyntaxProvider();

            SetupSqlCe(path, logger);
            SetupSqlServer(logger);
        }
        public void Can_Map_Name_Property()
        {
            // Arrange
            var sqlSyntaxProvider = new SqlCeSyntaxProvider();

            // Act
            string column = new PropertyGroupMapper().Map(sqlSyntaxProvider, "Name");

            // Assert
            Assert.That(column, Is.EqualTo("[cmsPropertyTypeGroup].[text]"));
        }
示例#11
0
        public void Equals_Method_For_Value_Gets_Escaped()
        {
            var sqlSyntax = new SqlCeSyntaxProvider();
            Expression <Func <IUser, bool> > predicate = user => user.Username.Equals("*****@*****.**");
            var modelToSqlExpressionHelper             = new ModelToSqlExpressionVisitor <IUser>(SqlContext.SqlSyntax, Mappers);
            var result = modelToSqlExpressionHelper.Visit(predicate);

            Debug.Print("Model to Sql ExpressionHelper: \n" + result);

            Assert.AreEqual("upper([umbracoUser].[userLogin]) = upper(@0)", result);
            Assert.AreEqual("*****@*****.**", modelToSqlExpressionHelper.GetSqlParameters()[0]);
        }
示例#12
0
        /// <summary>
        /// Inheritors can override this if they wish to create a custom application context
        /// </summary>
        protected virtual void SetupApplicationContext()
        {
            var sqlSyntax   = new SqlCeSyntaxProvider();
            var repoFactory = new RepositoryFactory(CacheHelper.CreateDisabledCacheHelper(), Logger, sqlSyntax, SettingsForTests.GenerateMockSettings());

            var evtMsgs = new TransientMessagesFactory();

            ApplicationContext.Current = new ApplicationContext(
                //assign the db context
                new DatabaseContext(new DefaultDatabaseFactory(Core.Configuration.GlobalSettings.UmbracoConnectionName, Logger),
                                    Logger, sqlSyntax, "System.Data.SqlServerCe.4.0"),
                //assign the service context
                new ServiceContext(repoFactory, new PetaPocoUnitOfWorkProvider(Logger), new FileUnitOfWorkProvider(), new PublishingStrategy(evtMsgs, Logger), CacheHelper, Logger, evtMsgs),
                CacheHelper,
                ProfilingLogger)
            {
                IsReady = true
            };
        }
示例#13
0
        private void MockForGetPagedUsers()
        {
            Mock.Get(Current.SqlContext)
            .Setup(x => x.Query <IUser>())
            .Returns(new Query <IUser>(Current.SqlContext));

            var syntax = new SqlCeSyntaxProvider();

            Mock.Get(Current.SqlContext)
            .Setup(x => x.SqlSyntax)
            .Returns(syntax);

            var mappers = new MapperCollection(new []
            {
                new UserMapper()
            });

            Mock.Get(Current.SqlContext)
            .Setup(x => x.Mappers)
            .Returns(mappers);
        }
示例#14
0
        private void MockForGetPagedUsers()
        {
            Mock.Get(Current.SqlContext)
            .Setup(x => x.Query <IUser>())
            .Returns(new Query <IUser>(Current.SqlContext));

            var syntax = new SqlCeSyntaxProvider();

            Mock.Get(Current.SqlContext)
            .Setup(x => x.SqlSyntax)
            .Returns(syntax);

            var mappers = new MapperCollection(new []
            {
                new UserMapper(new Lazy <ISqlContext>(() => Current.SqlContext), new ConcurrentDictionary <Type, ConcurrentDictionary <string, string> >())
            });

            Mock.Get(Current.SqlContext)
            .Setup(x => x.Mappers)
            .Returns(mappers);
        }
示例#15
0
        /// <summary>
        /// Gets a mocked IUmbracoDatabaseFactory.
        /// </summary>
        /// <returns>An IUmbracoDatabaseFactory.</returns>
        /// <param name="configured">A value indicating whether the factory is configured.</param>
        /// <param name="canConnect">A value indicating whether the factory can connect to the database.</param>
        /// <remarks>This is just a void factory that has no actual database.</remarks>
        public IUmbracoDatabaseFactory GetDatabaseFactoryMock(bool configured = true, bool canConnect = true)
        {
            var sqlSyntax  = new SqlCeSyntaxProvider();
            var sqlContext = Mock.Of <ISqlContext>();

            Mock.Get(sqlContext).Setup(x => x.SqlSyntax).Returns(sqlSyntax);

            var databaseFactoryMock = new Mock <IUmbracoDatabaseFactory>();

            databaseFactoryMock.Setup(x => x.Configured).Returns(configured);
            databaseFactoryMock.Setup(x => x.CanConnect).Returns(canConnect);
            databaseFactoryMock.Setup(x => x.SqlContext).Returns(sqlContext);

            // can create a database - but don't try to use it!
            if (configured && canConnect)
            {
                databaseFactoryMock.Setup(x => x.CreateDatabase()).Returns(GetUmbracoSqlCeDatabase(Mock.Of <ILogger>()));
            }

            return(databaseFactoryMock.Object);
        }
        protected virtual ApplicationContext CreateApplicationContext()
        {
            var sqlSyntax   = new SqlCeSyntaxProvider();
            var repoFactory = new RepositoryFactory(CacheHelper, Logger, sqlSyntax, SettingsForTests.GenerateMockSettings());

            var dbFactory          = new DefaultDatabaseFactory(Constants.System.UmbracoConnectionName, Logger);
            var scopeProvider      = new ScopeProvider(dbFactory);
            var evtMsgs            = new TransientMessagesFactory();
            var applicationContext = new ApplicationContext(
                //assign the db context
                new DatabaseContext(scopeProvider, Logger, sqlSyntax, Constants.DatabaseProviders.SqlCe),
                //assign the service context
                new ServiceContext(repoFactory, new PetaPocoUnitOfWorkProvider(scopeProvider), CacheHelper, Logger, evtMsgs),
                CacheHelper,
                ProfilingLogger)
            {
                IsReady = true
            };

            return(applicationContext);
        }
        public ExternalLoginStore()
        {
            if (!System.IO.File.Exists(IOHelper.MapPath("~/App_Data/UmbracoIdentity.sdf")))
            {
                using (var en = new SqlCeEngine(ConnString))
                {
                    en.CreateDatabase();
                }    
            }

            _db = new UmbracoDatabase(ConnString, "System.Data.SqlServerCe.4.0");
            if (!_db.TableExist("ExternalLogins"))
            {
                //unfortunately we'll get issues if we just try this because of differing sql syntax providers. In newer
                // umbraco versions we'd just use the DatabaseSchemaHelper. So in the meantime we have to just 
                // do this manually and use reflection :(;
                //_db.CreateTable<ExternalLoginDto>();

                var sqlceProvider = new SqlCeSyntaxProvider();
                CreateTable(false, typeof (ExternalLoginDto), sqlceProvider);
            }
        }
示例#18
0
        public virtual void Initialize()
        {
            Current.Reset();

            var container = RegisterFactory.Create();

            var ioHelper   = IOHelper.Default;
            var logger     = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>());
            var typeFinder = new TypeFinder(Mock.Of <ILogger>());
            var typeLoader = new TypeLoader(ioHelper, typeFinder, NoAppCache.Instance,
                                            new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")),
                                            logger,
                                            false);

            var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run));

            composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>());
            composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>());

            composition.RegisterUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .AddCoreMappers();

            composition.RegisterUnique <ISqlContext>(_ => SqlContext);

            var factory = Current.Factory = composition.CreateFactory();

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
            var sqlSyntax       = new SqlCeSyntaxProvider();

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, new Lazy <IMapperCollection>(() => factory.GetInstance <IMapperCollection>()));
            Mappers    = factory.GetInstance <IMapperCollection>();

            SetUp();
        }
        public ExternalLoginStore()
        {
            if (!System.IO.File.Exists(IOHelper.MapPath("~/App_Data/UmbracoIdentity.sdf")))
            {
                using (var en = new SqlCeEngine(ConnString))
                {
                    en.CreateDatabase();
                }
            }

            _db = new UmbracoDatabase(ConnString, "System.Data.SqlServerCe.4.0");
            if (!_db.TableExist("ExternalLogins"))
            {
                //unfortunately we'll get issues if we just try this because of differing sql syntax providers. In newer
                // umbraco versions we'd just use the DatabaseSchemaHelper. So in the meantime we have to just
                // do this manually and use reflection :(;
                //_db.CreateTable<ExternalLoginDto>();

                var sqlceProvider = new SqlCeSyntaxProvider();
                CreateTable(false, typeof(ExternalLoginDto), sqlceProvider);
            }
        }
        public virtual void Initialize()
        {
            var services = TestHelper.GetRegister();

            var ioHelper   = TestHelper.IOHelper;
            var logger     = new ProfilingLogger(Mock.Of <ILogger <ProfilingLogger> >(), Mock.Of <IProfiler>());
            var typeFinder = TestHelper.GetTypeFinder();
            var typeLoader = new TypeLoader(typeFinder, NoAppCache.Instance,
                                            new DirectoryInfo(ioHelper.MapPath(Constants.SystemDirectories.TempData)),
                                            Mock.Of <ILogger <TypeLoader> >(),
                                            logger,
                                            false);

            var composition = new UmbracoBuilder(services, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader());


            services.AddUnique <ILogger>(_ => Mock.Of <ILogger>());
            services.AddUnique <ILoggerFactory>(_ => NullLoggerFactory.Instance);
            services.AddUnique <IProfiler>(_ => Mock.Of <IProfiler>());
            services.AddUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .AddCoreMappers();

            services.AddUnique <ISqlContext>(_ => SqlContext);

            var factory = Current.Factory = TestHelper.CreateServiceProvider(composition);

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
            var sqlSyntax       = new SqlCeSyntaxProvider(Options.Create(new GlobalSettings()));

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, new Lazy <IMapperCollection>(() => factory.GetRequiredService <IMapperCollection>()));
            Mappers    = factory.GetRequiredService <IMapperCollection>();

            SetUp();
        }
示例#21
0
        public virtual void Initialize()
        {
            Current.Reset();

            var sqlSyntax = new SqlCeSyntaxProvider();

            var container = RegisterFactory.Create();

            var logger     = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>());
            var typeLoader = new TypeLoader(NullCacheProvider.Instance,
                                            LocalTempStorage.Default,
                                            logger,
                                            false);

            var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run));

            composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>());
            composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>());

            composition.RegisterUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .Add(() => composition.TypeLoader.GetAssignedMapperTypes());

            var factory = Current.Factory = composition.CreateFactory();

            Mappers = factory.GetInstance <IMapperCollection>();

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, Mappers);

            SetUp();
        }
示例#22
0
        public void Can_Generate_Delete_SubQuery_Statement()
        {
            var sqlSyntax = new SqlCeSyntaxProvider();

            var mediaObjectType = Guid.Parse(Constants.ObjectTypes.Media);
            var subQuery        = new Sql()
                                  .Select("DISTINCT cmsContentXml.nodeId")
                                  .From <ContentXmlDto>(sqlSyntax)
                                  .InnerJoin <NodeDto>(sqlSyntax)
                                  .On <ContentXmlDto, NodeDto>(sqlSyntax, left => left.NodeId, right => right.NodeId)
                                  .Where <NodeDto>(dto => dto.NodeObjectType == mediaObjectType);

            var sqlOutput = sqlSyntax.GetDeleteSubquery("cmsContentXml", "nodeId", subQuery);

            Assert.AreEqual(@"DELETE FROM [cmsContentXml] WHERE [nodeId] IN (SELECT [nodeId] FROM (SELECT DISTINCT cmsContentXml.nodeId
FROM [cmsContentXml]
INNER JOIN [umbracoNode]
ON [cmsContentXml].[nodeId] = [umbracoNode].[id]
WHERE (([umbracoNode].[nodeObjectType] = @0))) x)".Replace(Environment.NewLine, " ").Replace("\n", " ").Replace("\r", " "),
                            sqlOutput.SQL.Replace(Environment.NewLine, " ").Replace("\n", " ").Replace("\r", " "));

            Assert.AreEqual(1, sqlOutput.Arguments.Length);
            Assert.AreEqual(mediaObjectType, sqlOutput.Arguments[0]);
        }
示例#23
0
        public void Can_Generate_Create_Table_Statement()
        {
            var sqlSyntax = new SqlCeSyntaxProvider();

            var type       = typeof(NodeDto);
            var definition = DefinitionFactory.GetTableDefinition(sqlSyntax, type);

            string create     = sqlSyntax.Format(definition);
            string primaryKey = sqlSyntax.FormatPrimaryKey(definition);
            var    indexes    = sqlSyntax.Format(definition.Indexes);
            var    keys       = sqlSyntax.Format(definition.ForeignKeys);

            Debug.Print(create);
            Debug.Print(primaryKey);
            foreach (var sql in keys)
            {
                Debug.Print(sql);
            }

            foreach (var sql in indexes)
            {
                Debug.Print(sql);
            }
        }
        private void CreateTable(bool overwrite, Type modelType, SqlCeSyntaxProvider syntaxProvider)
        {
            var defFactoryType  = Type.GetType("Umbraco.Core.Persistence.DatabaseModelDefinitions.DefinitionFactory,Umbraco.Core", true);
            var tableDefinition = (TableDefinition)defFactoryType.CallStaticMethod("GetTableDefinition", modelType);

            var tableName = tableDefinition.Name;

            string createSql           = syntaxProvider.Format(tableDefinition);
            string createPrimaryKeySql = syntaxProvider.FormatPrimaryKey(tableDefinition);
            var    foreignSql          = syntaxProvider.Format(tableDefinition.ForeignKeys);
            var    indexSql            = syntaxProvider.Format(tableDefinition.Indexes);

            var tableExist = _db.TableExist(tableName);

            if (overwrite && tableExist)
            {
                _db.DropTable(tableName);
                tableExist = false;
            }

            if (tableExist == false)
            {
                using (var transaction = _db.GetTransaction())
                {
                    //Execute the Create Table sql
                    int created = _db.Execute(new Sql(createSql));
                    LogHelper.Info <ExternalLoginStore>(string.Format("Create Table sql {0}:\n {1}", created, createSql));

                    //If any statements exists for the primary key execute them here
                    if (!string.IsNullOrEmpty(createPrimaryKeySql))
                    {
                        int createdPk = _db.Execute(new Sql(createPrimaryKeySql));
                        LogHelper.Info <ExternalLoginStore>(string.Format("Primary Key sql {0}:\n {1}", createdPk, createPrimaryKeySql));
                    }

                    //Turn on identity insert if db provider is not mysql
                    if (syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
                    {
                        _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", syntaxProvider.GetQuotedTableName(tableName))));
                    }

                    //Turn off identity insert if db provider is not mysql
                    if (syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
                    {
                        _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", syntaxProvider.GetQuotedTableName(tableName))));
                    }

                    //Loop through foreignkey statements and execute sql
                    foreach (var sql in foreignSql)
                    {
                        int createdFk = _db.Execute(new Sql(sql));
                        LogHelper.Info <ExternalLoginStore>(string.Format("Create Foreign Key sql {0}:\n {1}", createdFk, sql));
                    }

                    //Loop through index statements and execute sql
                    foreach (var sql in indexSql)
                    {
                        int createdIndex = _db.Execute(new Sql(sql));
                        LogHelper.Info <ExternalLoginStore>(string.Format("Create Index sql {0}:\n {1}", createdIndex, sql));
                    }

                    transaction.Complete();
                }
            }

            LogHelper.Info <ExternalLoginStore>(string.Format("New table '{0}' was created", tableName));
        }
        public async System.Threading.Tasks.Task GetCurrentUser_Fips()
        {
            ApiController CtrlFactory(HttpRequestMessage message, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper helper)
            {
                //setup some mocks
                var userServiceMock = Mock.Get(Current.Services.UserService);

                userServiceMock.Setup(service => service.GetUserById(It.IsAny <int>()))
                .Returns(() => null);

                if (Thread.GetDomain().GetData(".appPath") != null)
                {
                    HttpContext.Current = new HttpContext(new SimpleWorkerRequest("", "", new StringWriter()));
                }
                else
                {
                    var baseDir = Current.IOHelper.MapPath("", false).TrimEnd(Current.IOHelper.DirSepChar);
                    HttpContext.Current = new HttpContext(new SimpleWorkerRequest("/", baseDir, "", "", new StringWriter()));
                }
                Current.IOHelper.ForceNotHosted = true;
                var usersController = new AuthenticationController(
                    Factory.GetInstance <IGlobalSettings>(),
                    umbracoContextAccessor,
                    Factory.GetInstance <ISqlContext>(),
                    Factory.GetInstance <ServiceContext>(),
                    Factory.GetInstance <AppCaches>(),
                    Factory.GetInstance <IProfilingLogger>(),
                    Factory.GetInstance <IRuntimeState>(),
                    helper);

                return(usersController);
            }

            Mock.Get(Current.SqlContext)
            .Setup(x => x.Query <IUser>())
            .Returns(new Query <IUser>(Current.SqlContext));

            var syntax = new SqlCeSyntaxProvider();

            Mock.Get(Current.SqlContext)
            .Setup(x => x.SqlSyntax)
            .Returns(syntax);

            var mappers = new MapperCollection(new[]
            {
                new UserMapper(new Lazy <ISqlContext>(() => Current.SqlContext), new ConcurrentDictionary <Type, ConcurrentDictionary <string, string> >())
            });

            Mock.Get(Current.SqlContext)
            .Setup(x => x.Mappers)
            .Returns(mappers);

            // Testing what happens if the system were configured to only use FIPS-compliant algorithms
            var typ               = typeof(CryptoConfig);
            var flds              = typ.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
            var haveFld           = flds.FirstOrDefault(f => f.Name == "s_haveFipsAlgorithmPolicy");
            var isFld             = flds.FirstOrDefault(f => f.Name == "s_fipsAlgorithmPolicy");
            var originalFipsValue = CryptoConfig.AllowOnlyFipsAlgorithms;

            try
            {
                if (!originalFipsValue)
                {
                    haveFld.SetValue(null, true);
                    isFld.SetValue(null, true);
                }

                var runner   = new TestRunner(CtrlFactory);
                var response = await runner.Execute("Authentication", "GetCurrentUser", HttpMethod.Get);

                var obj = JsonConvert.DeserializeObject <UserDetail>(response.Item2);
                Assert.AreEqual(-1, obj.UserId);
            }
            finally
            {
                if (!originalFipsValue)
                {
                    haveFld.SetValue(null, false);
                    isFld.SetValue(null, false);
                }
            }
        }
        private void CreateTable(bool overwrite, Type modelType, SqlCeSyntaxProvider syntaxProvider)
        {
            var defFactoryType = Type.GetType("Umbraco.Core.Persistence.DatabaseModelDefinitions.DefinitionFactory,Umbraco.Core", true);
            var tableDefinition = (TableDefinition)defFactoryType.CallStaticMethod("GetTableDefinition", modelType);

            var tableName = tableDefinition.Name;

            string createSql = syntaxProvider.Format(tableDefinition);
            string createPrimaryKeySql = syntaxProvider.FormatPrimaryKey(tableDefinition);
            var foreignSql = syntaxProvider.Format(tableDefinition.ForeignKeys);
            var indexSql = syntaxProvider.Format(tableDefinition.Indexes);

            var tableExist = _db.TableExist(tableName);
            if (overwrite && tableExist)
            {
                _db.DropTable(tableName);
                tableExist = false;
            }

            if (tableExist == false)
            {
                using (var transaction = _db.GetTransaction())
                {
                    //Execute the Create Table sql
                    int created = _db.Execute(new Sql(createSql));
                    LogHelper.Info<ExternalLoginStore>(string.Format("Create Table sql {0}:\n {1}", created, createSql));

                    //If any statements exists for the primary key execute them here
                    if (!string.IsNullOrEmpty(createPrimaryKeySql))
                    {
                        int createdPk = _db.Execute(new Sql(createPrimaryKeySql));
                        LogHelper.Info<ExternalLoginStore>(string.Format("Primary Key sql {0}:\n {1}", createdPk, createPrimaryKeySql));
                    }

                    //Turn on identity insert if db provider is not mysql
                    if (syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
                        _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} ON ", syntaxProvider.GetQuotedTableName(tableName))));
                    
                    //Turn off identity insert if db provider is not mysql
                    if (syntaxProvider.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
                        _db.Execute(new Sql(string.Format("SET IDENTITY_INSERT {0} OFF;", syntaxProvider.GetQuotedTableName(tableName))));
                    
                    //Loop through foreignkey statements and execute sql
                    foreach (var sql in foreignSql)
                    {
                        int createdFk = _db.Execute(new Sql(sql));
                        LogHelper.Info<ExternalLoginStore>(string.Format("Create Foreign Key sql {0}:\n {1}", createdFk, sql));
                    }

                    //Loop through index statements and execute sql
                    foreach (var sql in indexSql)
                    {
                        int createdIndex = _db.Execute(new Sql(sql));
                        LogHelper.Info<ExternalLoginStore>(string.Format("Create Index sql {0}:\n {1}", createdIndex, sql));
                    }

                    transaction.Complete();
                }
            }

            LogHelper.Info<ExternalLoginStore>(string.Format("New table '{0}' was created", tableName));
        }