Esempio n. 1
0
        public System.Web.Http.IHttpActionResult DeleteSeason(int id)
        {
            UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;

            try
            {
                db.Delete <Season>(id);
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok());
        }
Esempio n. 2
0
        /// <summary>
        /// Adds the approval group nodes to the tree.
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="queryStrings">The query strings.</param>
        public void AddApprovalGroupsToTree(TreeNodeCollection nodes, FormDataCollection queryStrings)
        {
            UmbracoDatabase      db         = ApplicationContext.Current.DatabaseContext.Database;
            List <UserGroupPoco> userGroups = db.Fetch <UserGroupPoco>(SqlHelpers.GroupsForTree).OrderBy(x => x.Name).ToList();

            if (!userGroups.Any())
            {
                return;
            }

            foreach (UserGroupPoco group in userGroups)
            {
                nodes.Add(CreateTreeNode(group.GroupId.ToString(), "approvalGroups", queryStrings, group.Name, "icon-users", false, $"{EditGroupRoute}{group.GroupId}"));
            }
        }
Esempio n. 3
0
        public ExternalLoginStore()
        {
            if (identityStoreConnection == null)
            {
                throw new ConfigurationException("UmbracoIdentityStore is not set in the configuration");
            }

            _db = new UmbracoDatabase(identityStoreConnection.ConnectionString, "System.Data.SqlClient");
            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>();
            }
        }
Esempio n. 4
0
        public MigrationContext(
            [NotNull] IServiceContext services,
            [NotNull] UmbracoDatabase database,
            [NotNull] CacheHelper cacheHelper,
            [NotNull] IMigrationRecordRepository migrationRecords,
            [NotNull] MigrationConfiguration configuration,
            [CanBeNull] IMigrationLogger logger = null
            )
        {
            Services         = Argument.NotNull(nameof(services), services);
            Database         = Argument.NotNull(nameof(database), database);
            MigrationRecords = Argument.NotNull(nameof(migrationRecords), migrationRecords);
            Configuration    = Argument.NotNull(nameof(configuration), configuration);
            Logger           = logger;

            _cacheHelper = cacheHelper;
        }
Esempio n. 5
0
        public System.Web.Http.IHttpActionResult DeleteAllStatsByGameId(int id)
        {
            UmbracoDatabase db           = ApplicationContext.DatabaseContext.Database;
            var             affectedRows = new SqlParameter("@intResult", System.Data.SqlDbType.Int);

            affectedRows.Direction = System.Data.ParameterDirection.Output;
            try
            {
                var records = db.Fetch <Stat>(";EXEC DeleteAllStatsByGameId @0, @1 OUTPUT", id, affectedRows);
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok(affectedRows.Value));
        }
Esempio n. 6
0
        public async Task DatabaseError_WillStillAttemptFirstDeliverableThenCreateTableAgain()
        {
            var ex = Substitute.For <DbException>();

            var provider = Substitute.For <ISqlSyntaxProvider>();

            provider.Format(Arg.Any <ICollection <ForeignKeyDefinition> >()).Returns(new List <string>());
            provider.Format(Arg.Any <ICollection <IndexDefinition> >()).Returns(new List <string>());
            provider.DoesTableExist(Arg.Any <Database>(), Arg.Any <string>()).Returns(_ => { throw ex; }, _ => true);

            SqlSyntaxContext.SqlSyntaxProvider = provider;

            var conn = Substitute.For <IDbConnection>();
            var cmd  = Substitute.For <IDbCommand>();

            cmd.ExecuteScalar().Returns(1);
            conn.CreateCommand().Returns(cmd);
            var db = new UmbracoDatabase(conn);

            var    settings = Substitute.For <IChauffeurSettings>();
            string s;

            settings.TryGetChauffeurDirectory(out s).Returns(x =>
            {
                x[0] = @"c:\foo";
                return(true);
            });

            var writer = new MockTextWriter();

            var fs = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\foo\bar.delivery", new MockFileData("install") }
            });

            var host = Substitute.For <IChauffeurHost>();

            host.Run(Arg.Any <string[]>()).Returns(Task.FromResult(DeliverableResponse.Continue));

            var deliverable = new DeliveryDeliverable(null, writer, db, settings, fs, host);

            await deliverable.Run(null, null);

            cmd.Received().CommandText = Arg.Any <string>();
        }
Esempio n. 7
0
        private void CreateFieldMappings(UmbracoDatabase db)
        {
            var sql      = "SELECT * FROM gigya_settings";
            var settings = db.Fetch <GigyaUmbracoModuleSettings>(sql);
            var currentGlobalSettings = settings.Select(i => i.GlobalParameters).ToList();

            // create field mappings if don't already exist
            foreach (var setting in settings)
            {
                var mappings = !string.IsNullOrEmpty(setting.MappingFields) ? JsonConvert.DeserializeObject <List <MappingField> >(setting.MappingFields) : new List <MappingField>();
                CreateFieldMapping(ref mappings, _umbracoFirstName, Gigya.Umbraco.Module.Constants.GigyaFields.FirstName);
                CreateFieldMapping(ref mappings, _umbracoLastName, Gigya.Umbraco.Module.Constants.GigyaFields.LastName);
                CreateFieldMapping(ref mappings, _umbracoAge, _gigyaAge);

                setting.MappingFields = JsonConvert.SerializeObject(mappings);
                db.Save(setting);
            }
        }
Esempio n. 8
0
        public AzureSearchReindexStatus ReIndexContent(string sessionId)
        {
            List <int> contentIds;
            List <int> mediaIds;
            List <int> memberIds;

            using (var db = new UmbracoDatabase("umbracoDbDSN"))
            {
                contentIds = db.Fetch <int>(@"select distinct cmsContent.NodeId
                    from cmsContent, umbracoNode where
                    cmsContent.nodeId = umbracoNode.id and
                    umbracoNode.nodeObjectType = 'C66BA18E-EAF3-4CFF-8A22-41B16D66A972'");

                mediaIds = db.Fetch <int>(@"select distinct cmsContent.NodeId
                    from cmsContent, umbracoNode where
                    cmsContent.nodeId = umbracoNode.id and
                    umbracoNode.nodeObjectType = 'B796F64C-1F99-4FFB-B886-4BF4BC011A9C'");

                memberIds = db.Fetch <int>(@"select distinct cmsContent.NodeId
                    from cmsContent, umbracoNode where
                    cmsContent.nodeId = umbracoNode.id and
                    umbracoNode.nodeObjectType = '39EB0F98-B348-42A1-8662-E7EB18487560'");
            }



            var contentCount = contentIds.Count;

            var path = Path.Combine(_path, @"App_Data\MoriyamaAzureSearch\" + sessionId);

            EnsurePath(path);

            System.IO.File.WriteAllText(Path.Combine(path, "content.json"), JsonConvert.SerializeObject(contentIds));
            System.IO.File.WriteAllText(Path.Combine(path, "media.json"), JsonConvert.SerializeObject(mediaIds));
            System.IO.File.WriteAllText(Path.Combine(path, "member.json"), JsonConvert.SerializeObject(memberIds));

            return(new AzureSearchReindexStatus
            {
                SessionId = sessionId,
                DocumentCount = contentCount,
                Error = false,
                Finished = false
            });
        }
Esempio n. 9
0
        // initializes a new scope, replacing a NoScope instance
        public Scope(ScopeProvider scopeProvider, NoScope noScope,
                     ScopeContext scopeContext,
                     IsolationLevel isolationLevel           = IsolationLevel.Unspecified,
                     RepositoryCacheMode repositoryCacheMode = RepositoryCacheMode.Unspecified,
                     IEventDispatcher eventDispatcher        = null,
                     bool?scopeFileSystems = null,
                     bool callContext      = false)
            : this(scopeProvider, null, scopeContext, false, isolationLevel, repositoryCacheMode, eventDispatcher, scopeFileSystems, callContext)
        {
            // steal everything from NoScope
            _database = noScope.DatabaseOrNull;
            _messages = noScope.MessagesOrNull;

            // make sure the NoScope can be replaced ie not in a transaction
            if (_database != null && _database.InTransaction)
            {
                throw new Exception("NoScope instance is not free.");
            }
        }
Esempio n. 10
0
        public void CreateDatabaseSchema(DatabaseType dbType, bool?skipInstaller)
        {
            //Depending on DB Type - Change Provider
            if (dbType == DatabaseType.MySQL)
            {
                SqlSyntaxContext.SqlSyntaxProvider = new MySqlSyntaxProvider();
            }
            else if (dbType == DatabaseType.SQLCE)
            {
                SqlSyntaxContext.SqlSyntaxProvider = new SqlCeSyntaxProvider();

                //Create a path to an Umbraco.sdf file in App_Data
                var path = Path.Combine(umbracoSitePath, "App_Data", "Umbraco.sdf");

                //Modified Connection String for CE creation
                var modConnection = string.Format("Data Source={0};Flush Interval=1;", path);

                //Update connection string
                connectionString = modConnection;
            }
            else
            {
                SqlSyntaxContext.SqlSyntaxProvider = new SqlServerSyntaxProvider();
            }

            //Create a new Umbraco DB object using connection details
            var db = new UmbracoDatabase(connectionString, providerName);

            //Create DB Schema
            //Get the method we want to run
            var methodToRun = typeof(PetaPocoExtensions).GetMethod("CreateDatabaseSchema", BindingFlags.Static | BindingFlags.NonPublic);

            //Invoke the Method - CreateDatabaseSchema(db, false)
            methodToRun.Invoke(null, new object[] { db, false });


            //Only Add/Update default admin user of admin/admin
            if (skipInstaller == true)
            {
                //Add/update default admin user of admin/admin
                db.Update <UserDto>("set userPassword = @password where id = @id", new { password = "******", id = 0 });
            }
        }
Esempio n. 11
0
        private void ValidateAttendanceSetOrThrow(AttendanceSet attendanceSet, UmbracoDatabase db)
        {
            if (attendanceSet.StructuralGroupId <= 0)
            {
                throw new Exception("Invalid group specified");
            }
            var requiredMembers = MemberHelper.GetMembers(ApplicationContext.DatabaseContext.Database, Services.MemberService, attendanceSet.StructuralGroupId, "Student");

            if (attendanceSet.AttendanceRecords.Select(a => a.MemberId).Except(requiredMembers.Select(m => m.Id)).Any() ||
                requiredMembers.Select(m => m.Id).Except(attendanceSet.AttendanceRecords.Select(a => a.MemberId)).Any())
            {
                throw new Exception("Attendance has not been captured for all members of the group");
            }

            if (!attendanceSet.AttendanceRecords.All(a => a.Attendance == (int)Attendance.Absent || a.Attendance == (int)Attendance.Present))
            {
                throw new Exception("Invalid present/absent status");
            }
        }
Esempio n. 12
0
        private static void Upgrade00to01(UmbracoDatabase db)
        {
            //TODO: Add new columns to the ContactMessage table
            //TODO: Add a new table called ContactorDbVersion
            //Create a record in ContactorDbVersion and make it version 1

            db.Execute(
                "ALTER TABLE ContactMessage ADD " +
                "PhoneNumber NVARCHAR(255) NULL, " +
                "WebsiteUrl NVARCHAR(255) NULL, " +
                "CompanyName NVARCHAR(255) NULL, " +
                "Location NVARCHAR(255) NULL");

            db.Execute(
                "CREATE TABLE uContactorVersion (DbVersion INT)");

            db.Execute(
                "INSERT INTO uContactorVersion values(1)");
        }
Esempio n. 13
0
        public async Task FoundDeliveryNotPreviouslyRun_WillBeGivenToTheHost()
        {
            var provider = Substitute.For <ISqlSyntaxProvider>();

            provider.DoesTableExist(Arg.Any <Database>(), Arg.Any <string>()).Returns(true);

            SqlSyntaxContext.SqlSyntaxProvider = provider;

            var    settings = Substitute.For <IChauffeurSettings>();
            string s;

            settings.TryGetChauffeurDirectory(out s).Returns(x =>
            {
                x[0] = @"c:\foo";
                return(true);
            });

            var cmd = Substitute.For <IDbCommand>();

            cmd.ExecuteScalar().Returns(1);
            var conn = Substitute.For <IDbConnection>();

            conn.CreateCommand().Returns(cmd);
            var db = new UmbracoDatabase(conn);

            var writer = new MockTextWriter();

            var deliverableScript = "foo";
            var fs = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"c:\foo\bar.delivery", new MockFileData(deliverableScript) }
            });

            var host = Substitute.For <IChauffeurHost>();

            host.Run(Arg.Any <string[]>()).Returns(Task.FromResult(DeliverableResponse.Continue));

            var deliverable = new DeliveryDeliverable(null, writer, db, settings, fs, host);

            await deliverable.Run(null, null);

            host.Received(1).Run(Arg.Any <string[]>()).IgnoreAwaitForNSubstituteAssertion();
        }
Esempio n. 14
0
        public AzureSearchReindexStatus ReIndexMedia(string sessionId, int page)
        {
            var file = SessionFile(sessionId, "media.json");

            if (!File.Exists(file))
            {
                List <int> mediaIds;
                using (var db = new UmbracoDatabase("umbracoDbDSN"))
                {
                    mediaIds = db.Fetch <int>(@"select distinct cmsContent.NodeId
                        from cmsContent, umbracoNode where
                        cmsContent.nodeId = umbracoNode.id and
                        umbracoNode.nodeObjectType = 'B796F64C-1F99-4FFB-B886-4BF4BC011A9C'");
                }

                WriteFile(file, mediaIds);
            }

            return(ReIndex("media.json", sessionId, page));
        }
Esempio n. 15
0
        public AzureSearchReindexStatus ReIndexMember(string sessionId, int page)
        {
            var file = SessionFile(sessionId, "member.json");

            if (!File.Exists(file))
            {
                List <int> memberIds;
                using (var db = new UmbracoDatabase("umbracoDbDSN"))
                {
                    memberIds = db.Fetch <int>(@"select distinct cmsContent.NodeId
                    from cmsContent, umbracoNode where
                    cmsContent.nodeId = umbracoNode.id and
                    umbracoNode.nodeObjectType = '39EB0F98-B348-42A1-8662-E7EB18487560'");
                }

                WriteFile(file, memberIds);
            }

            return(ReIndex("member.json", sessionId, page));
        }
Esempio n. 16
0
        public bool PreviousMigrationsHaveFinishedCleanly()
        {
            try
            {
                UmbracoDatabase.OpenSharedConnection();

                using (var transaction = GetTransaction())
                {
                    var result = UmbracoDatabase.FirstOrDefault <MigrationHistory>("WHERE Completed = 0");
                    var previousMigrationsHaveFinishedCleanly = result == null;

                    transaction.Complete();
                    return(previousMigrationsHaveFinishedCleanly);
                }
            }
            finally
            {
                UmbracoDatabase.CloseSharedConnection();
            }
        }
Esempio n. 17
0
    private static void MigrateDataIdsToUdis(UmbracoDatabase database)
    {
        string sql = @"SELECT cmsPropertyData.id, cmsPropertyData.contentNodeId, cmsPropertyType.alias, dataNvarchar, dataNtext, dataInt, cmsDocument.*
            FROM cmsPropertyData
            JOIN cmsPropertyType ON cmsPropertyType.id = cmsPropertyData.propertytypeid
            JOIN cmsDataType ON cmsDataType.nodeId = cmsPropertyType.dataTypeId
            JOIN cmsContentVersion ON cmsContentVersion.VersionId = cmsPropertyData.versionId
            JOIN umbracoNode ON umbracoNode.id = cmsContentVersion.ContentId
            JOIN cmsDocument ON cmsDocument.nodeId = umbracoNode.id
            WHERE cmsDataType.propertyEditorAlias IN ('Umbraco.MultiUrlPicker')
            AND (dataNtext IS NOT NULL) AND (dataNtext LIKE '%""id"":%')
            AND (cmsDocument.published=1 OR cmsDocument.newest=1 OR cmsDocument.updateDate > (SELECT updateDate FROM cmsDocument AS innerDoc WHERE innerDoc.nodeId = cmsDocument.nodeId AND innerDoc.published=1 AND newest=1))
            ORDER BY contentNodeId, cmsDataType.propertyEditorAlias";

        var urlPickerDataToMigrate = database.Query <Row>(sql).ToList();

        if (urlPickerDataToMigrate.Any())
        {
            foreach (var propertyData in urlPickerDataToMigrate)
            {
                IEnumerable <Umbraco.Web.Models.Link> multiUrls;

                if (!string.IsNullOrEmpty(propertyData.dataNtext))
                {
                    multiUrls = BuildMultiUrlLinks(propertyData.dataNtext);
                }
                else
                {
                    LogHelper.Info(typeof(MultiUrlPickerIdToUdiMigrator), () => $"MigrateIdsToUdis (node id: {propertyData.contentNodeId}) skipping property {propertyData.alias} - null dataNtext");
                    continue;
                }

                var linksValue = ToDataValue(multiUrls);

                LogHelper.Info(typeof(MultiUrlPickerIdToUdiMigrator), () => $"MigrateIdsToUdis (node id: {propertyData.contentNodeId}) converting property {propertyData.alias} from {propertyData.dataNtext} to {linksValue}");
                database.Execute("UPDATE cmsPropertyData SET dataNtext=@0 WHERE id=@1", linksValue, propertyData.id);
            }

            LogHelper.Info(typeof(MultiUrlPickerIdToUdiMigrator), () => $"MigrateIdsToUdis: migrated Umbraco.MultiUrlPicker datatypes.");
        }
    }
Esempio n. 18
0
        internal DatabaseSchemaResult ValidateDatabaseSchema()
        {
            if (_configured == false || (string.IsNullOrEmpty(_connectionString) || string.IsNullOrEmpty(ProviderName)))
            {
                return(new DatabaseSchemaResult());
            }

            if (_result == null)
            {
                if (SystemUtilities.GetCurrentTrustLevel() != AspNetHostingPermissionLevel.Unrestricted &&
                    ProviderName == Constants.DatabaseProviders.MySql)
                {
                    throw new InvalidOperationException("Cannot use MySql in Medium Trust configuration");
                }

                var database = new UmbracoDatabase(_connectionString, ProviderName, _logger);
                var dbSchema = new DatabaseSchemaCreation(database, _logger, SqlSyntax);
                _result = dbSchema.ValidateSchema();
            }
            return(_result);
        }
Esempio n. 19
0
        public async Task NoExistingDatabase_WillCreateTable()
        {
            var provider = Substitute.For <ISqlSyntaxProvider>();

            provider.Format(Arg.Any <ICollection <ForeignKeyDefinition> >()).Returns(new List <string>());
            provider.Format(Arg.Any <ICollection <IndexDefinition> >()).Returns(new List <string>());
            provider.DoesTableExist(Arg.Any <Database>(), Arg.Any <string>()).Returns(false);

            SqlSyntaxContext.SqlSyntaxProvider = provider;

            var conn = Substitute.For <IDbConnection>();
            var db   = new UmbracoDatabase(conn);

            var settings = Substitute.For <IChauffeurSettings>();

            var deliverable = new DeliveryDeliverable(null, new MockTextWriter(), db, settings, null, null);

            await deliverable.Run(null, null);

            provider.Received().DoesTableExist(Arg.Is((Database)db), Arg.Any <string>());
        }
Esempio n. 20
0
        private void DisposeLastScope()
        {
            // figure out completed
            var completed = _completed.HasValue && _completed.Value;

            // deal with database
            var databaseException = false;

            if (_database != null)
            {
                try
                {
                    if (completed)
                    {
                        _database.CompleteTransaction();
                    }
                    else
                    {
                        _database.AbortTransaction();
                    }
                }
                catch
                {
                    databaseException = true;
                    throw;
                }
                finally
                {
                    _database.Dispose();
                    _database = null;

                    if (databaseException)
                    {
                        RobustExit(false, true);
                    }
                }
            }

            RobustExit(completed, false);
        }
Esempio n. 21
0
        public System.Web.Http.IHttpActionResult UpdateGame(Game game)
        {
            UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;

            try
            {
                db.Update(new Game
                {
                    Game_Id       = game.Game_Id,
                    Season_Id     = game.Season_Id,
                    Game_Location = game.Game_Location,
                    Opposing_Team = game.Opposing_Team,
                    Game_Date     = game.Game_Date
                });
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok());
        }
        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);
            }
        }
Esempio n. 23
0
        public System.Web.Http.IHttpActionResult AddGame(Game game)
        {
            UmbracoDatabase db        = ApplicationContext.DatabaseContext.Database;
            var             gameToAdd = new Game
            {
                Season_Id     = game.Season_Id,
                Game_Date     = game.Game_Date,
                Game_Location = game.Game_Location,
                Opposing_Team = game.Opposing_Team
            };

            try
            {
                db.Insert(gameToAdd);
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok(gameToAdd));
        }
Esempio n. 24
0
        public System.Web.Http.IHttpActionResult UpdateSeason(Season season)
        {
            UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;

            try
            {
                db.Update(new Season
                {
                    Season_Id         = season.Season_Id,
                    Season_Title      = season.Season_Title,
                    Season_Location   = season.Season_Location,
                    Season_Start_Date = season.Season_Start_Date,
                    Season_End_Date   = season.Season_End_Date
                });
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok());
        }
        private void SetupSqlCe(string path, ILogger logger)
        {
            var dbName = string.Concat("Umb", Guid.NewGuid(), ".sdf");

            AppDomain.CurrentDomain.SetData("DataDirectory", path);
            var sqlCeConnectionString = $"Datasource=|DataDirectory|\\{dbName};Flush Interval=1;";

            _dbFile = Path.Combine(path, dbName);

            //only create the db one time
            if (_initDbBytes == null)
            {
                using (var engine = new SqlCeEngine(sqlCeConnectionString))
                {
                    engine.CreateDatabase();
                }

                //use the db  to create the initial schema so we can reuse in each bench
                using (_dbSqlCe = new UmbracoDatabase(
                           sqlCeConnectionString,
                           Constants.DatabaseProviders.SqlCe,
                           logger))
                {
                    var creation = new DatabaseSchemaCreation(_dbSqlCe, logger, _sqlCeSyntax);
                    creation.InitializeDatabaseSchema();
                }
                _initDbBytes = File.ReadAllBytes(_dbFile);
            }
            else
            {
                File.WriteAllBytes(_dbFile, _initDbBytes);
            }

            //create the db
            _dbSqlCe = new UmbracoDatabase(
                sqlCeConnectionString,
                Constants.DatabaseProviders.SqlCe,
                logger);
        }
Esempio n. 26
0
        private void TestDB(DatabaseContext.DatabaseType dbType, string connectionString, string providerName)
        {
            //Let's try....
            try
            {
                //Try and create & connect to the Database
                //If Advanced provider name etc all in the connection string
                if (dbType == DatabaseContext.DatabaseType.Advanced)
                {
                    var db = new UmbracoDatabase(connectionString);
                }
                else
                {
                    //Providing both connection string & provider name
                    var db = new UmbracoDatabase(connectionString, providerName);

                    //Now open the connection to test it out...
                    //Exception will fire if it can connect
                    db.OpenSharedConnection();
                }


                //Show a Success Message Box
                MessageBox.Show("Database Connection Sucessful", "Database Connection Test", MessageBoxButton.OK, MessageBoxImage.Information);

                //Enable Button
                CreateProjectBtn.IsEnabled = true;
            }
            catch (Exception ex)
            {
                var error = string.Format("Database Connection Error: {0}", ex.Message);

                //Show an Error Message Box
                MessageBox.Show(error, "Database Connection Test", MessageBoxButton.OK, MessageBoxImage.Error);

                //Disable Button
                CreateProjectBtn.IsEnabled = false;
            }
        }
        public void Issue8361Test()
        {
            var logger = new DebugDiagnosticsLogger();

            //Setup the MigrationRunner
            var migrationRunner = new MigrationRunner(
                Mock.Of <IMigrationEntryService>(),
                logger,
                new SemVersion(7, 4, 0),
                new SemVersion(7, 5, 0),
                Constants.System.UmbracoMigrationName,

                //pass in explicit migrations
                new DeleteRedirectUrlTable(SqlSyntax, logger),
                new AddRedirectUrlTable(SqlSyntax, logger)
                );

            var db = new UmbracoDatabase("Datasource=|DataDirectory|UmbracoPetaPocoTests.sdf;Flush Interval=1;", Constants.DatabaseProviders.SqlCe, Logger);

            var upgraded = migrationRunner.Execute(db, DatabaseProviders.SqlServerCE, true);

            Assert.IsTrue(upgraded);
        }
        //[System.Web.Http.HttpPost]
        public void SaveFile()
        {
            var           myContext = Request.TryGetHttpContext();
            List <string> keys      = new List <string>();

            if (myContext.Success)

            {
                HttpPostedFileBase myFile = myContext.Result.Request.Files["file"];
                if (myFile == null)
                {
                    throw new HttpException("invalid file");
                }
                else
                {
                    StreamReader csvreader = new StreamReader(myFile.InputStream);


                    while (!csvreader.EndOfStream)
                    {
                        var line = csvreader.ReadLine();
                        if (line != "Key")
                        {
                            keys.Add(line);
                        }
                    }
                }
                UmbracoDatabase db     = ApplicationContext.DatabaseContext.Database;
                var             remove = new Sql("DELETE FROM cmsDictionary");
                int             rem    = db.Execute(remove);
                foreach (string item in keys)
                {
                    var insert = new Sql("INSERT INTO cmsDictionary VALUES (NEWID(), null,'" + item + "')");
                    int res    = db.Execute(insert);
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Handles checking and running migrations
        /// </summary>
        /// <param name="db">Database context</param>
        /// <param name="migrationService">Migration service</param>
        private void HandleMigrations(UmbracoDatabase db, IMigrationEntryService migrationService)
        {
            var latestMigrationVersion = new SemVersion(0, 0, 0);

            // get all migrations for "Redirects" already executed
            var migrations = migrationService.GetAll(REDIRECTS_TABLE_NAME);

            // get the latest migration for "Redirects" executed
            var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();

            if (latestMigration != null)
            {
                latestMigrationVersion = latestMigration.Version;
            }

            if (this._targetVersion == latestMigrationVersion)
            {
                return;
            }

            var migrationsRunner = new MigrationRunner(
                migrationService,
                ApplicationContext.Current.ProfilingLogger.Logger,
                latestMigrationVersion,
                this._targetVersion,
                REDIRECTS_TABLE_NAME);

            try
            {
                migrationsRunner.Execute(db);
            }
            catch (HttpException e) {}
            catch (Exception e)
            {
                LogHelper.Error <MigrationRunner>("Error running Redirects migration", e);
            }
        }
Esempio n. 30
0
        public bool HasMigrationExecuted(IUmbracoMigration migration)
        {
            var migrationName = migration.GetType().Name;

            try
            {
                UmbracoDatabase.OpenSharedConnection();

                using (var transaction = GetTransaction())
                {
                    var migrationHistory     = UmbracoDatabase.FirstOrDefault <MigrationHistory>("WHERE Name = @Name", new { Name = migrationName });
                    var hasMigrationExecuted = migrationHistory != null;

                    Log.Debug(string.Format("HasMigrationExecuted for {0} is {1}", migrationName, hasMigrationExecuted));

                    transaction.Complete();
                    return(hasMigrationExecuted);
                }
            }
            finally
            {
                UmbracoDatabase.CloseSharedConnection();
            }
        }
		/// <summary>
		/// Creates a new unit of work instance
		/// </summary>
		/// <param name="database"></param>
		/// <remarks>
		/// This should normally not be used directly and should be created with the UnitOfWorkProvider
		/// </remarks>
		internal PetaPocoUnitOfWork(UmbracoDatabase database)
		{
			Database = database;
			_key = Guid.NewGuid();
			InstanceId = Guid.NewGuid();
		}