Пример #1
0
		public UmbracoDatabase CreateDatabase()
		{
			//no http context, create the singleton global object
			if (HttpContext.Current == null)
			{
                if (_nonHttpInstance == null)
				{
					lock (Locker)
					{
						//double check
                        if (_nonHttpInstance == null)
						{
                            _nonHttpInstance = string.IsNullOrEmpty(ConnectionString) == false && string.IsNullOrEmpty(ProviderName) == false
						                          ? new UmbracoDatabase(ConnectionString, ProviderName)
						                          : new UmbracoDatabase(_connectionStringName);
						}
					}
				}
                return _nonHttpInstance;
			}

			//we have an http context, so only create one per request
			if (HttpContext.Current.Items.Contains(typeof(DefaultDatabaseFactory)) == false)
			{
			    HttpContext.Current.Items.Add(typeof (DefaultDatabaseFactory),
			                                  string.IsNullOrEmpty(ConnectionString) == false && string.IsNullOrEmpty(ProviderName) == false
			                                      ? new UmbracoDatabase(ConnectionString, ProviderName)
			                                      : new UmbracoDatabase(_connectionStringName));
			}
			return (UmbracoDatabase)HttpContext.Current.Items[typeof(DefaultDatabaseFactory)];
		}
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this._db = ApplicationContext.DatabaseContext.Database;

            //Get the current version from appsettings if its there
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

            if (config.AppSettings.Settings.AllKeys.Contains("EventCalendarVersion"))//WebConfigurationManager.AppSettings.AllKeys.Contains("EventCalendarVersion"))
            {
                oldVersion = new Version(WebConfigurationManager.AppSettings["EventCalendarVersion"]);
                if (newVersion != oldVersion)
                {
                    config.AppSettings.Settings.Remove("EventCalendarVersion");
                    config.Save();
                    config.AppSettings.Settings.Add("EventCalendarVersion", newVersion.ToString());
                    config.Save();
                }
            }
            else
            {                
                config.AppSettings.Settings.Add("EventCalendarVersion", newVersion.ToString());
                config.Save();
            }

            //Create section and language code
            this.CreateSection();
            this.addLanguagekey();
            this.AddSectionDashboard();

            //Create database tables
            this.CreateTable();

            this.RunMigrations();
        }
        public async Task NoDeliveriesFound_DoesntRequireHost()
        {
            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 conn = Substitute.For<IDbConnection>();
            var db = new UmbracoDatabase(conn);

            var writer = new MockTextWriter();

            var fs = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                {@"c:\foo\bar.txt", new MockFileData("This is not a deliverable")}
            });

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

            await deliverable.Run(null, null);

            Assert.That(writer.Messages.Count(), Is.EqualTo(1));
        }
Пример #4
0
        protected override void OnInit(EventArgs e)
        {
            this._db = ApplicationContext.Current.DatabaseContext.Database;

            // Tab setup
            FirstTab = tabControl.NewTabPage("First");
            FirstTab.Controls.Add(SettingsPane);

            SecondTab = tabControl.NewTabPage("Second");
            SecondTab.Controls.Add(CreateEventPane);

            ThirdTab = tabControl.NewTabPage("Third");
            ThirdTab.Controls.Add(ShowEventsPane);

            //save button
            ImageButton save = FirstTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            ImageButton save2 = SecondTab.Menu.NewImageButton();
            save2.Click += new ImageClickEventHandler(this.save_event_click);
            save2.AlternateText = "Save";
            save2.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";
        }
Пример #5
0
 public MockDatabaseUnitOfWork()
 {
     CommitCalled = false;
     InsertCalled = false;
     DeleteCalled = false;
     _database = null;
 }
Пример #6
0
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //try
            //{
            //    var runner = new MigrationRunner(new System.Version("2.0"), new System.Version("2.0.1"), "UpdateEventsForCategorys");
            //    var upgraded = runner.Execute(applicationContext.DatabaseContext.Database, true);
            //}
            //catch (Exception ex) { LogHelper.Error<DatabaseUp>("Failed to do the migration", ex); }

            this._db = applicationContext.DatabaseContext.Database;

            if (this._db != null)
            {
                //Create Calendar table
                try
                {
                    if (!this._db.TableExist("ec_calendars"))
                    {
                        this._db.CreateTable<EventCalendarBelle.Models.ECalendar>(false);
                        //Create first calendar
                        //ECalendar cal = new ECalendar() { Calendarname = "TestCalendar", DisplayOnSite = true, IsGCal = false, GCalFeedUrl = "", Color = "#0E0E0E" };
                        //this._db.Save(cal);
                    }
                }
                catch (Exception ex)
                { }

                //Create Locations table
                try
                {
                    if (!this._db.TableExist("ec_locations"))
                    {
                        this._db.CreateTable<EventLocation>(false);
                    }
                }
                catch (Exception ex)
                { }

                try
                {
                    if (!this._db.TableExist("ec_events"))
                    {
                        this._db.CreateTable<Event>(false);
                    }
                }
                catch (Exception ex)
                { }

                if (!this._db.TableExist("ec_recevents"))
                {
                    this._db.CreateTable<RecurringEvent>(false);
                }

                if (!this._db.TableExist("ec_eventdescriptions"))
                {
                    this._db.CreateTable<EventDescription>(false);
                }
            }
        }
Пример #7
0
 public ContactForm()
 {
     _database = ApplicationContext.Current.DatabaseContext.Database;
     if (!_database.TableExist("ContactForm"))
     {
         _database.CreateTable<ContactFormPoco>();
     }
 }
 public void Init()
 {
     var syntax = (DbSyntax)Enum.Parse(typeof(DbSyntax), ConfigurationManager.AppSettings["syntax"]);
     var worker = new DbPreTestDataWorker {SqlSyntax = syntax };
     _database = worker.Database;
     var deletions = new DatabaseSchemaCreation(_database);
     deletions.UninstallDatabaseSchema();
 }
Пример #9
0
 public void Init()
 {
     var syntax = (DbSyntax)Enum.Parse(typeof(DbSyntax), ConfigurationManager.AppSettings["syntax"]);
     var worker = new DbPreTestDataWorker {SqlSyntax = syntax };
     var logger = Logger.CreateWithDefaultLog4NetConfiguration();
     var sqlSyntax = SqlSyntaxProviderTestHelper.SqlSyntaxProvider(syntax);
     _database = worker.Database;
     _databaseSchemaHelper = new MerchelloDatabaseSchemaHelper(_database, logger, sqlSyntax);
 }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RepositoryFactory"/> class.
        /// </summary>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <param name="runtimeCache">
        /// The runtimeCache.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Throws exception if either database or runtimeCache is null
        /// </exception>
        public RepositoryFactory(UmbracoDatabase database, IRuntimeCacheProvider runtimeCache)
        {
            if (database == null) throw new ArgumentNullException("database");
            if (runtimeCache == null) throw new ArgumentNullException("runtimeCache");

            this._runtimeCache = runtimeCache;

            _database = database;
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this._db = ApplicationContext.DatabaseContext.Database;

            //Create section and language code
            this.CreateSection();
            this.addLanguagekey();

            //Create database tables
            this.CreateTable();
        }
        protected override void OnInit(EventArgs e)
        {
            this._db = ApplicationContext.Current.DatabaseContext.Database;

            // Tab setup
            FirstTab = TabView1.NewTabPage("Settings");
            FirstTab.Controls.Add(SettingsPane);

            //save button
            ImageButton save = FirstTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";
        }
Пример #13
0
 public DeliveryDeliverable(
     TextReader reader,
     TextWriter writer,
     UmbracoDatabase database,
     IChauffeurSettings settings,
     IFileSystem fileSystem,
     IChauffeurHost host
 )
     : base(reader, writer)
 {
     this.database = database;
     this.settings = settings;
     this.fileSystem = fileSystem;
     this.host = host;
 }
        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>();
            }
        }
Пример #15
0
        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
            var engine = new SqlCeEngine(connectionString);
            if (File.Exists(databaseDataPath) == false)
                engine.CreateDatabase();

            SqlSyntaxContext.SqlSyntaxProvider = new SqlCeSyntaxProvider();

            _database = new UmbracoDatabase(connectionString, "System.Data.SqlServerCe.4.0");

            // First remove anything in the database
            var creation = new DatabaseSchemaCreation(_database);
            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 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>());
        }
Пример #17
0
        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 ContactFormRepo()
 {
     _db = ApplicationContext.Current.DatabaseContext.Database;
 }
Пример #19
0
 /// <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();
 }
Пример #20
0
 private void CreateAndSaveMediaXml(XElement xml, int id, UmbracoDatabase db)
 {
     var poco = new ContentXmlDto { NodeId = id, Xml = xml.ToString(SaveOptions.None) };
     var exists = db.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = id }) != null;
     int result = exists ? db.Update(poco) : Convert.ToInt32(db.Insert(poco));
 }
Пример #21
0
 public ScheduleRunner(UmbracoDatabase database) {
     _log = LogManager.GetLogger(GetType());
     _database = database;
 }
Пример #22
0
 private void CreateAndSaveContentXml(XElement xml, int id, UmbracoDatabase db)
 {
     var contentPoco = new ContentXmlDto { NodeId = id, Xml = xml.ToString(SaveOptions.None) };
     var contentExists = db.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsContentXml WHERE nodeId = @Id", new { Id = id }) != 0;
     int contentResult = contentExists ? db.Update(contentPoco) : Convert.ToInt32(db.Insert(contentPoco));
 }
Пример #23
0
		private static void SaveOrder(OrderData fetch, UmbracoDatabase db)
		{
			fetch.UpdateDate = DateTime.Now;

			db.Save(fetch);
		}
Пример #24
0
 public void Init()
 {
     var worker = new DbPreTestDataWorker();
     _database = worker.Database;
     _creation = new BaseDataCreation(_database);
 }
 public static bool TableExist(this UmbracoDatabase db, string tableName)
 {
     return(SqlSyntaxContext.SqlSyntaxProvider.DoesTableExist(db, tableName));
 }
Пример #26
0
        internal DatabaseSchemaResult ValidateDatabaseSchema()
        {
            if (_configured == false || (string.IsNullOrEmpty(_connectionString) || string.IsNullOrEmpty(ProviderName)))
                return new DatabaseSchemaResult();

            if (_result == null)
            {
                var database = new UmbracoDatabase(_connectionString, ProviderName);
                var dbSchema = new DatabaseSchemaCreation(database);
                _result = dbSchema.ValidateSchema();
            }
            return _result;
        }
Пример #27
0
        internal Result CreateDatabaseSchemaAndDataOrUpgrade()
        {
            if (_configured == false || (string.IsNullOrEmpty(_connectionString) || string.IsNullOrEmpty(ProviderName)))
            {
                return new Result
                           {
                               Message =
                                   "Database configuration is invalid. Please check that the entered database exists and that the provided username and password has write access to the database.",
                               Success = false,
                               Percentage = "10"
                           };
            }

            try
            {
                LogHelper.Info<DatabaseContext>("Database configuration status: Started");

                var message = string.Empty;

                var database = new UmbracoDatabase(_connectionString, ProviderName);
                var supportsCaseInsensitiveQueries = SqlSyntaxContext.SqlSyntaxProvider.SupportsCaseInsensitiveQueries(database);
                if (supportsCaseInsensitiveQueries  == false)
                {
                    message = "<p>&nbsp;</p><p>The database you're trying to use does not support case insensitive queries. <br />We currently do not support these types of databases.</p>" +
                              "<p>You can fix this by changing the following two settings in your my.ini file in your MySQL installation directory:</p>" +
                              "<pre>lower_case_table_names=1\nlower_case_file_system=1</pre><br />" +
                              "<p>Note: Make sure to check with your hosting provider if they support case insensitive queries as well.</p>" +
                              "<p>For more technical information on case sensitivity in MySQL, have a look at " +
                              "<a href='http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html'>the documentation on the subject</a></p>";

                    return new Result { Message = message, Success = false, Percentage = "15" };
                }
                else if (supportsCaseInsensitiveQueries == null)
                {
                    message = "<p>&nbsp;</p><p>Warning! Could not check if your database type supports case insensitive queries. <br />We currently do not support these databases that do not support case insensitive queries.</p>" +
                              "<p>You can check this by looking for the following two settings in your my.ini file in your MySQL installation directory:</p>" +
                              "<pre>lower_case_table_names=1\nlower_case_file_system=1</pre><br />" +
                              "<p>Note: Make sure to check with your hosting provider if they support case insensitive queries as well.</p>" +
                              "<p>For more technical information on case sensitivity in MySQL, have a look at " +
                              "<a href='http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html'>the documentation on the subject</a></p>";
                }
                else
                {
                    if (SqlSyntaxContext.SqlSyntaxProvider.GetType() == typeof(MySqlSyntaxProvider))
                    {
                        message = "<p>&nbsp;</p><p>Congratulations, the database step ran successfully!</p>" +
                                  "<p>Note: You're using MySQL and the database instance you're connecting to seems to support case insensitive queries.</p>" +
                                  "<p>However, your hosting provider may not support this option. Umbraco does not currently support MySQL installs that do not support case insensitive queries</p>" +
                                  "<p>Make sure to check with your hosting provider if they support case insensitive queries as well.</p>" +
                                  "<p>They can check this by looking for the following two settings in the my.ini file in their MySQL installation directory:</p>" +
                                  "<pre>lower_case_table_names=1\nlower_case_file_system=1</pre><br />" +
                                  "<p>For more technical information on case sensitivity in MySQL, have a look at " +
                                  "<a href='http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html'>the documentation on the subject</a></p>";
                    }
                }

                var schemaResult = ValidateDatabaseSchema();
                var installedVersion = schemaResult.DetermineInstalledVersion();
                

                //If Configuration Status is empty and the determined version is "empty" its a new install - otherwise upgrade the existing
                if (string.IsNullOrEmpty(GlobalSettings.ConfigurationStatus) && installedVersion.Equals(new Version(0, 0, 0)))
                {
                    database.CreateDatabaseSchema();
                    message = message + "<p>Installation completed!</p>";
                }
                else
                {
                    var configuredVersion = string.IsNullOrEmpty(GlobalSettings.ConfigurationStatus)
                                                ? installedVersion
                                                : new Version(GlobalSettings.ConfigurationStatus);
                    var targetVersion = UmbracoVersion.Current;
                    var runner = new MigrationRunner(configuredVersion, targetVersion, GlobalSettings.UmbracoMigrationName);
                    var upgraded = runner.Execute(database, true);
                    message = message + "<p>Upgrade completed!</p>";
                }

                LogHelper.Info<DatabaseContext>("Database configuration status: " + message);

                return new Result { Message = message, Success = true, Percentage = "100" };
            }
            catch (Exception ex)
            {
                LogHelper.Info<DatabaseContext>("Database configuration failed with the following error and stack trace: " + ex.Message + "\n" + ex.StackTrace);

                if (_result != null)
                {
                    LogHelper.Info<DatabaseContext>("The database schema validation produced the following summary: \n" + _result.GetSummary());
                }

                return new Result
                           {
                               Message =
                                   "The database configuration failed with the following message: " + ex.Message +
                                   "\n Please check log file for additional information (can be found in '/App_Data/Logs/UmbracoTraceLog.txt')",
                               Success = false,
                               Percentage = "90"
                           };
            }
        }
        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 });
            }
        }
Пример #29
0
 private void CreateAndSavePreviewXml(XElement xml, int id, Guid version, UmbracoDatabase db)
 {
     var previewPoco = new PreviewXmlDto
     {
         NodeId = id,
         Timestamp = DateTime.Now,
         VersionId = version,
         Xml = xml.ToString(SaveOptions.None)
     };
     var previewExists =
         db.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsPreviewXml WHERE nodeId = @Id AND versionId = @Version",
                                         new { Id = id, Version = version }) != 0;
     int previewResult = previewExists
                             ? db.Update<PreviewXmlDto>(
                                 "SET xml = @Xml, timestamp = @Timestamp WHERE nodeId = @Id AND versionId = @Version",
                                 new
                                     {
                                         Xml = previewPoco.Xml,
                                         Timestamp = previewPoco.Timestamp,
                                         Id = previewPoco.NodeId,
                                         Version = previewPoco.VersionId
                                     })
                             : Convert.ToInt32(db.Insert(previewPoco));
 }
Пример #30
0
 public void Init()
 {
     var syntax = (DbSyntax)Enum.Parse(typeof(DbSyntax), ConfigurationManager.AppSettings["syntax"]);
     var worker = new DbPreTestDataWorker {SqlSyntax = syntax };
     _database = worker.Database;
 }
Пример #31
0
		private static OrderData GetOrCreateOrderWithGuid(Guid orderId, UmbracoDatabase db)
		{
			var fetch = db.Fetch<OrderData>(new Sql().Select("*").From("uWebshopOrders").Where((OrderData o) => o.UniqueId == orderId)).FirstOrDefault() ?? new OrderData {CreateDate = DateTime.Now};
			return fetch;
		}