private void Init() { MainDom = new MainDom(ProfilingLogger.Logger); MainDom.Acquire(); //Create the lazy value to resolve whether or not the application is 'configured' _configured = new Lazy <bool>(() => { try { var configStatus = ConfigurationStatus; var currentVersion = UmbracoVersion.GetSemanticVersion(); var ok = //we are not configured if this is null string.IsNullOrWhiteSpace(configStatus) == false //they must match && configStatus == currentVersion; if (ok) { //The versions are the same in config, but are they the same in the database. We can only check this // if we have a db context available, if we don't then we are not installed anyways if (DatabaseContext.IsDatabaseConfigured && DatabaseContext.CanConnect) { var found = Services.MigrationEntryService.FindEntry(Constants.System.UmbracoMigrationName, UmbracoVersion.GetSemanticVersion()); if (found == null) { //we haven't executed this migration in this environment, so even though the config versions match, // this db has not been updated. ProfilingLogger.Logger.Debug <ApplicationContext>(string.Format("The migration for version: '{0} has not been executed, there is no record in the database", currentVersion.ToSemanticString())); ok = false; } } } else { ProfilingLogger.Logger.Debug <ApplicationContext>(string.Format("CurrentVersion different from configStatus: '{0}','{1}'", currentVersion.ToSemanticString(), configStatus)); } return(ok); } catch (Exception ex) { LogHelper.Error <ApplicationContext>("Error determining if application is configured, returning false", ex); return(false); } }); }
/// <summary> /// /// </summary> /// <returns></returns> public static string GetCacheBustHash() { //make a hash of umbraco and client dependency version //in case the user bypasses the installer and just bumps the web.config or clientdep config //if in debug mode, always burst the cache if (GlobalSettings.DebugMode) { return(DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).GenerateHash()); } var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); return(string.Format("{0}.{1}", version, ClientDependencySettings.Instance.Version).GenerateHash()); }
public async Task <JObject> GetRemoteDashboardContent(string section, string baseUrl = "https://dashboard.umbraco.org/") { var context = UmbracoContext.Current; if (context == null) { throw new HttpResponseException(HttpStatusCode.InternalServerError); } var user = Security.CurrentUser; var allowedSections = string.Join(",", user.AllowedSections); var language = user.Language; var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); var url = string.Format(baseUrl + "{0}?section={0}&allowed={1}&lang={2}&version={3}", section, allowedSections, language, version); var key = "umbraco-dynamic-dashboard-" + language + allowedSections.Replace(",", "-") + section; var content = ApplicationContext.ApplicationCache.RuntimeCache.GetCacheItem <JObject>(key); var result = new JObject(); if (content != null) { result = content; } else { //content is null, go get it try { //fetch dashboard json and parse to JObject var json = await HttpClient.GetStringAsync(url); content = JObject.Parse(json); result = content; ApplicationContext.ApplicationCache.RuntimeCache.InsertCacheItem <JObject>(key, () => result, new TimeSpan(0, 30, 0)); } catch (HttpRequestException ex) { LogHelper.Debug <DashboardController>(string.Format("Error getting dashboard content from '{0}': {1}\n{2}", url, ex.Message, ex.InnerException)); //it's still new JObject() - we return it like this to avoid error codes which triggers UI warnings ApplicationContext.ApplicationCache.RuntimeCache.InsertCacheItem <JObject>(key, () => result, new TimeSpan(0, 5, 0)); } } return(result); }
public override async Task <DeliverableResponse> Run(string command, string[] args) { if (!TryFindCurrentDbVersion(out var currentVersion)) { await Out.WriteLineAsync("Can't upgrade as there is no configured version"); return(DeliverableResponse.FinishedWithError); } var targetVersion = UmbracoVersion.GetSemanticVersion(); if (currentVersion == targetVersion) { await Out.WriteLineAsync($"Version is up to date {currentVersion} no work todo"); return(DeliverableResponse.FinishedWithError); } await Out.WriteLineAsync($"Upgrading from {currentVersion} to {targetVersion}"); var upgraded = migrationRunner.Execute(currentVersion, targetVersion); if (!upgraded) { await Out.WriteLineAsync("Upgrading failed, see log for full details"); return(DeliverableResponse.FinishedWithError); } chauffeurSettings.TryGetSiteRootDirectory(out string path); var configPath = Path.Combine(path, "web.config"); XmlDocument xmld = xmlDocumentWrapper.LoadDocument(configPath); XmlElement status = (XmlElement)xmld.SelectSingleNode("/configuration/appSettings/add[@key='umbracoConfigurationStatus']"); if (status != null) { status.SetAttribute("value", targetVersion.ToString()); } xmlDocumentWrapper.SaveDocument(xmld, configPath); await Out.WriteLineAsync("Upgrading completed"); return(DeliverableResponse.Continue); }
public override void Initialize() { InitializeFirstRunFlags(); var path = TestHelper.CurrentAssemblyDirectory; AppDomain.CurrentDomain.SetData("DataDirectory", path); //disable cache var cacheHelper = CacheHelper.CreateDisabledCacheHelper(); var dbFactory = new DefaultDatabaseFactory( GetDbConnectionString(), GetDbProviderName(), Logger); var repositoryFactory = new RepositoryFactory(cacheHelper, Logger, SqlSyntax, SettingsForTests.GenerateMockSettings()); var evtMsgs = new TransientMessagesFactory(); _appContext = new ApplicationContext( //assign the db context new DatabaseContext(dbFactory, Logger, SqlSyntax, "System.Data.SqlServerCe.4.0"), //assign the service context new ServiceContext(repositoryFactory, new PetaPocoUnitOfWorkProvider(dbFactory), new FileUnitOfWorkProvider(), new PublishingStrategy(evtMsgs, Logger), cacheHelper, Logger, evtMsgs), cacheHelper, ProfilingLogger) { IsReady = true }; base.Initialize(); using (ProfilingLogger.TraceDuration <BaseDatabaseFactoryTest>("init")) { //TODO: Somehow make this faster - takes 5s + DatabaseContext.Initialize(dbFactory.ProviderName, dbFactory.ConnectionString); CreateSqlCeDatabase(); InitializeDatabase(); //ensure the configuration matches the current version for tests SettingsForTests.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString(); } }
public async Task <IEnumerable <Lesson> > GetLessons(string path) { //information for the request, so we could in the future filter by user, allowed sections, langugae and user-type var user = Security.CurrentUser; var userType = user.UserType.Alias; var allowedSections = string.Join(",", user.AllowedSections); var language = user.Language; var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); //construct the url and cache key var url = string.Format("https://our.umbraco.org/Umbraco/Documentation/Lessons/GetDocsForPath?path={0}&userType={1}&allowedSections={2}&lang={3}&version={4}", path, userType, allowedSections, language, version); var key = "umbraco-lessons-" + userType + language + allowedSections.Replace(",", "-") + path; var result = new List <Lesson>(); Func <List <Lesson> > fetchLesson = () => { try { using (var web = new HttpClient()) { //fetch dashboard json and parse to JObject var json = web.GetStringAsync(url); result = JsonConvert.DeserializeObject <IEnumerable <Lesson> >(json.Result).ToList(); } } catch (HttpRequestException ex) { //Log it so we are aware there was an issue LogHelper.Debug <LessonsController>(string.Format("Error getting lesson content from '{0}': {1}\n{2}", url, ex.Message, ex.InnerException)); //The result is still a new/empty JObject() - So we will return it like this to avoid error codes which triggers UI warnings //So this will cache an empty response until cache expires } return(result); }; //Get cache item or add new cache item with func result = ApplicationContext.ApplicationCache.RuntimeCache.GetCacheItem <List <Lesson> >(key, fetchLesson, new TimeSpan(0, 30, 0)); return(result); }
/// <summary> /// Returns the server variables regarding the application state /// </summary> /// <returns></returns> private Dictionary <string, object> GetApplicationState() { if (ApplicationContext.IsConfigured == false) { return(null); } var app = new Dictionary <string, object> { { "assemblyVersion", UmbracoVersion.AssemblyVersion } }; var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); app.Add("version", version); app.Add("cdf", ClientDependencySettings.Instance.Version); //useful for dealing with virtual paths on the client side when hosted in virtual directories especially app.Add("applicationPath", HttpContext.Request.ApplicationPath.EnsureEndsWith('/')); return(app); }
public override void Initialize() { InitializeFirstRunFlags(); var path = TestHelper.CurrentAssemblyDirectory; AppDomain.CurrentDomain.SetData("DataDirectory", path); // we probably don't need this here, as it's done in base.Initialize() already, // but these test classes are all weird, not going to change it now - v8 SafeCallContext.Clear(); _dbFactory = new DefaultDatabaseFactory( GetDbConnectionString(), GetDbProviderName(), Logger); // ensure we start tests in a clean state ie without any scope in context // anything that used a true 'Scope' would have removed it, but there could // be a rogue 'NoScope' there - and we want to make sure it is gone var scopeProvider = new ScopeProvider(null); if (scopeProvider.AmbientScope != null) { scopeProvider.AmbientScope.Dispose(); // removes scope from context } base.Initialize(); using (ProfilingLogger.TraceDuration <BaseDatabaseFactoryTest>("init")) { //TODO: Somehow make this faster - takes 5s + DatabaseContext.Initialize(_dbFactory.ProviderName, _dbFactory.ConnectionString); CreateSqlCeDatabase(); InitializeDatabase(); //ensure the configuration matches the current version for tests SettingsForTests.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString(); } }
public ActionResult Index() { if (ApplicationContext.Current.IsConfigured) { return(Redirect(SystemDirectories.Umbraco.EnsureEndsWith('/'))); } if (ApplicationContext.Current.IsUpgrading) { // Update ClientDependency version var clientDependencyConfig = new ClientDependencyConfiguration(_umbracoContext.Application.ProfilingLogger.Logger); var clientDependencyUpdated = clientDependencyConfig.UpdateVersionNumber( UmbracoVersion.GetSemanticVersion(), DateTime.UtcNow, "yyyyMMdd"); // Delete ClientDependency temp directories to make sure we get fresh caches var clientDependencyTempFilesDeleted = clientDependencyConfig.ClearTempFiles(HttpContext); var result = _umbracoContext.Security.ValidateCurrentUser(false); switch (result) { case ValidateRequestAttempt.FailedNoPrivileges: case ValidateRequestAttempt.FailedNoContextId: return(Redirect(SystemDirectories.Umbraco + "/AuthorizeUpgrade?redir=" + Server.UrlEncode(Request.RawUrl))); } } //gen the install base url ViewBag.InstallApiBaseUrl = Url.GetUmbracoApiService("GetSetup", "InstallApi", "UmbracoInstall").TrimEnd("GetSetup"); //get the base umbraco folder ViewBag.UmbracoBaseFolder = IOHelper.ResolveUrl(SystemDirectories.Umbraco); InstallHelper ih = new InstallHelper(_umbracoContext); ih.InstallStatus(false, ""); //always ensure full path (see NOTE in the class remarks) return(View(GlobalSettings.Path.EnsureEndsWith('/') + "install/views/index.cshtml")); }
public void Is_Not_Configured_By_Migration_Not_Found() { ConfigurationManager.AppSettings.Set("umbracoConfigurationStatus", UmbracoVersion.GetSemanticVersion().ToSemanticString()); var migrationEntryService = new Mock <IMigrationEntryService>(); migrationEntryService.Setup(x => x.FindEntry(It.IsAny <string>(), It.IsAny <SemVersion>())) .Returns((IMigrationEntry)null); var dbCtx = new Mock <DatabaseContext>(Mock.Of <IScopeProviderInternal>(), Mock.Of <ILogger>(), new SqlCeSyntaxProvider(), "test"); dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true); dbCtx.Setup(x => x.CanConnect).Returns(true); var appCtx = new ApplicationContext( dbCtx.Object, new ServiceContext(migrationEntryService: migrationEntryService.Object), CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>())); Assert.IsFalse(appCtx.IsConfigured); }
/// <summary> /// Returns the server variables regarding the application state /// </summary> /// <returns></returns> private Dictionary <string, object> GetApplicationState() { var app = new Dictionary <string, object> { { "assemblyVersion", UmbracoVersion.AssemblyVersion } }; var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); //the value is the hash of the version, cdf version and the configured state app.Add("cacheBuster", $"{version}.{_applicationContext.IsConfigured}.{ClientDependencySettings.Instance.Version}".GenerateHash()); app.Add("version", version); //useful for dealing with virtual paths on the client side when hosted in virtual directories especially app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/')); //add the server's GMT time offset in minutes app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes)); return(app); }
public override void Initialize() { base.Initialize(); //create the module _module = new UmbracoModule(); SettingsForTests.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString(); //SettingsForTests.ReservedPaths = "~/umbraco,~/install/"; //SettingsForTests.ReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd"; Directory.CreateDirectory(Path.GetDirectoryName(IOHelper.MapPath(SystemFiles.NotFoundhandlersConfig, false))); //create the not found handlers config using (var sw = File.CreateText(IOHelper.MapPath(SystemFiles.NotFoundhandlersConfig, false))) { sw.Write(@"<NotFoundHandlers> <notFound assembly='umbraco' type='SearchForAlias' /> <notFound assembly='umbraco' type='SearchForTemplate'/> <notFound assembly='umbraco' type='SearchForProfile'/> <notFound assembly='umbraco' type='handle404'/> </NotFoundHandlers>"); } }
protected void Page_Load(object sender, EventArgs e) { // Put user code to initialize the page here thisYear.Text = DateTime.Now.Year.ToString(CultureInfo.InvariantCulture); version.Text = UmbracoVersion.GetSemanticVersion().ToSemanticString(); }
public async Task CorrectSameVersionSelected_NothingDone() { var deliverable = new UpgradeDeliverable(null, writer, null, MigrationEntryService(new SemVersion(7, 1), UmbracoVersion.GetSemanticVersion(), new SemVersion(7, 3)), settings, xmlDocumentWrapper); var response = await deliverable.Run(null, null); Assert.Single(writer.Messages); Assert.Equal(DeliverableResponse.FinishedWithError, response); }
public IEnumerable <DiagnosticGroup> GetDiagnosticGroups() { List <DiagnosticGroup> groups = new List <DiagnosticGroup>(); int id = 0; var sections = new List <DiagnosticSection>(); var group = new DiagnosticGroup(id++, "Umbraco Configuration"); var section = new DiagnosticSection("Umbraco Version"); section.Diagnostics.Add(new Diagnostic("Current Version", UmbracoVersion.Current)); section.Diagnostics.Add(new Diagnostic("Assembly Version", UmbracoVersion.AssemblyVersion)); section.Diagnostics.Add(new Diagnostic("Current Comment", UmbracoVersion.CurrentComment)); section.Diagnostics.Add(new Diagnostic("Semantic Version", UmbracoVersion.GetSemanticVersion().ToSemanticString())); sections.Add(section); section = new DiagnosticSection("Umbraco Settings"); section.Diagnostics.Add(new Diagnostic("Debug Mode?", umbraco.GlobalSettings.DebugMode)); section.Diagnostics.Add(new Diagnostic("Trust Level", umbraco.GlobalSettings.ApplicationTrustLevel)); section.Diagnostics.Add(new Diagnostic("XML Content File", umbraco.GlobalSettings.ContentXML)); section.Diagnostics.Add(new Diagnostic("Storage Directory", umbraco.GlobalSettings.StorageDirectory)); section.Diagnostics.Add(new Diagnostic("Default UI Language", umbraco.GlobalSettings.DefaultUILanguage)); section.Diagnostics.Add(new Diagnostic("Profile URL", umbraco.GlobalSettings.ProfileUrl)); section.Diagnostics.Add(new Diagnostic("Update Check Period", umbraco.GlobalSettings.VersionCheckPeriod)); section.Diagnostics.Add(new Diagnostic("Path to Root", umbraco.GlobalSettings.FullpathToRoot)); section.AddDiagnostics(ConfigurationManager.AppSettings, false, key => key.StartsWith("umbraco", StringComparison.OrdinalIgnoreCase)); sections.Add(section); section = new DiagnosticSection("Content Settings"); var cs = UmbracoConfig.For.UmbracoSettings().Content; section.Diagnostics.Add(new Diagnostic("Clone XML Content?", cs.CloneXmlContent)); section.Diagnostics.Add(new Diagnostic("Continously Update XML Disk Cache?", cs.ContinouslyUpdateXmlDiskCache)); section.Diagnostics.Add(new Diagnostic("Default Doc Type Property", cs.DefaultDocumentTypeProperty)); section.Diagnostics.Add(new Diagnostic("Disallowed Upload Files", cs.DisallowedUploadFiles)); section.Diagnostics.Add(new Diagnostic("Enable Inherited Doc Types?", cs.EnableInheritedDocumentTypes)); section.Diagnostics.Add(new Diagnostic("Error 404 Page Ids", cs.Error404Collection.Select(x => x.ContentId.ToString()))); section.Diagnostics.Add(new Diagnostic("Ensure Unique Naming?", cs.EnsureUniqueNaming)); section.Diagnostics.Add(new Diagnostic("Force Safe Aliases?", cs.ForceSafeAliases)); section.Diagnostics.Add(new Diagnostic("Global Preview Storage Enabled?", cs.GlobalPreviewStorageEnabled)); section.Diagnostics.Add(new Diagnostic("Image AutoFill Aliases", cs.ImageAutoFillProperties.Select(x => x.Alias))); section.Diagnostics.Add(new Diagnostic("Image File Types", cs.ImageFileTypes)); section.Diagnostics.Add(new Diagnostic("Image Tage Allowed Attributes", cs.ImageTagAllowedAttributes)); section.Diagnostics.Add(new Diagnostic("Macro Error Behaviour", cs.MacroErrorBehaviour)); section.Diagnostics.Add(new Diagnostic("Notification Email Address", cs.NotificationEmailAddress)); section.Diagnostics.Add(new Diagnostic("Property Context Help Option", cs.PropertyContextHelpOption)); section.Diagnostics.Add(new Diagnostic("Resolve URLs From TextString?", cs.ResolveUrlsFromTextString)); section.Diagnostics.Add(new Diagnostic("Script Editor Disable?", cs.ScriptEditorDisable)); section.Diagnostics.Add(new Diagnostic("Script Folder Path", cs.ScriptFolderPath)); section.Diagnostics.Add(new Diagnostic("Script File Types", cs.ScriptFileTypes)); section.Diagnostics.Add(new Diagnostic("Tidy Char Encoding", cs.TidyCharEncoding)); section.Diagnostics.Add(new Diagnostic("Tidy Editor Content?", cs.TidyEditorContent)); section.Diagnostics.Add(new Diagnostic("Umbraco Library Cache Duration", cs.UmbracoLibraryCacheDuration)); section.Diagnostics.Add(new Diagnostic("Upload Allows Directories?", cs.UploadAllowDirectories)); section.Diagnostics.Add(new Diagnostic("Use Legacy XML Schema?", cs.UseLegacyXmlSchema)); section.Diagnostics.Add(new Diagnostic("XML Cache Enabled?", cs.XmlCacheEnabled)); section.Diagnostics.Add(new Diagnostic("XML Content Check for Disk Changes?", cs.XmlContentCheckForDiskChanges)); sections.Add(section); var dc = UmbracoConfig.For.UmbracoSettings().DistributedCall; section = new DiagnosticSection("Distributed Calls"); section.Diagnostics.Add(new Diagnostic("Enabled?", dc.Enabled)); section.Diagnostics.Add(new Diagnostic("User Id", dc.UserId)); foreach (var server in dc.Servers) { section.Diagnostics.Add(new Diagnostic(server.ServerName, String.Format("AppID: {0}, Address: {1}", server.AppId, server.ServerAddress))); } sections.Add(section); var dev = UmbracoConfig.For.UmbracoSettings().Developer; section = new DiagnosticSection("Developer"); section.Diagnostics.Add(new Diagnostic("App_Code File Extensions", dev.AppCodeFileExtensions.Select(x => x.Extension))); sections.Add(section); var lc = UmbracoConfig.For.UmbracoSettings().Logging; section = new DiagnosticSection("Logging"); section.Diagnostics.Add(new Diagnostic("Enable Logging?", lc.EnableLogging)); section.Diagnostics.Add(new Diagnostic("Enable Async Logging?", lc.EnableAsyncLogging)); section.Diagnostics.Add(new Diagnostic("Auto Clean Logs?", lc.AutoCleanLogs)); section.Diagnostics.Add(new Diagnostic("Cleaning Miliseconds", lc.CleaningMiliseconds)); section.Diagnostics.Add(new Diagnostic("Disabled Log Types", lc.DisabledLogTypes.Select(x => x.LogTypeAlias))); section.Diagnostics.Add(new Diagnostic("External Logger Configured?", lc.ExternalLoggerIsConfigured)); if (lc.ExternalLoggerIsConfigured) { section.Diagnostics.Add(new Diagnostic("External Logger Assembly", lc.ExternalLoggerAssembly)); section.Diagnostics.Add(new Diagnostic("External Logger Type", lc.ExternalLoggerType)); section.Diagnostics.Add(new Diagnostic("External Logger Enabled Audit Trail", lc.ExternalLoggerEnableAuditTrail)); } sections.Add(section); UmbracoDataService dataService = new UmbracoDataService(umbHelper); var servers = dataService.GetRegistredServers(); if (servers != null && servers.Any()) { section = new DiagnosticSection("Server Registration"); foreach (var server in servers) { section.Diagnostics.Add(new Diagnostic(server.ComputerName, server.ToDiagnostic())); } sections.Add(section); } var migrations = dataService.GetMigrations(); if (migrations != null && migrations.Any()) { section = new DiagnosticSection("Migration History"); foreach (var migration in migrations) { section.Diagnostics.Add(new Diagnostic(migration.Name, migration.ToDiagnostic())); } sections.Add(section); } var pro = UmbracoConfig.For.UmbracoSettings().Providers; section = new DiagnosticSection("Providers"); section.Diagnostics.Add(new Diagnostic("Default BackOffice User Provider", pro.DefaultBackOfficeUserProvider)); sections.Add(section); var rh = UmbracoConfig.For.UmbracoSettings().RequestHandler; section = new DiagnosticSection("Request Handler"); section.Diagnostics.Add(new Diagnostic("Add Trailing Slash?", rh.AddTrailingSlash)); section.Diagnostics.Add(new Diagnostic("Char Replacements?", rh.CharCollection.Select(c => String.Format("{0} {1}", c.Replacement, c.Char)))); section.Diagnostics.Add(new Diagnostic("Convert URLs to ASCII?", rh.ConvertUrlsToAscii)); section.Diagnostics.Add(new Diagnostic("Remove Double Slashes?", rh.RemoveDoubleDashes)); section.Diagnostics.Add(new Diagnostic("Use Domain Prefixes?", rh.UseDomainPrefixes)); sections.Add(section); var st = UmbracoConfig.For.UmbracoSettings().ScheduledTasks; section = new DiagnosticSection("Scheduled Tasks"); section.Diagnostics.Add(new Diagnostic("Base URL", st.BaseUrl)); foreach (var task in st.Tasks) { section.Diagnostics.Add(new Diagnostic(task.Alias, String.Format("{0} ({1} secs)", task.Url, task.Interval))); } sections.Add(section); var sec = UmbracoConfig.For.UmbracoSettings().Security; section = new DiagnosticSection("Security"); section.Diagnostics.Add(new Diagnostic("Auth Cookie Domain", sec.AuthCookieDomain)); section.Diagnostics.Add(new Diagnostic("Auth Cookie Name", sec.AuthCookieName)); section.Diagnostics.Add(new Diagnostic("Hide Disabled Users?", sec.HideDisabledUsersInBackoffice)); section.Diagnostics.Add(new Diagnostic("Keep User Logged In?", sec.KeepUserLoggedIn)); sections.Add(section); var temps = UmbracoConfig.For.UmbracoSettings().Templates; section = new DiagnosticSection("Templates"); section.Diagnostics.Add(new Diagnostic("Default Rendering Engine", temps.DefaultRenderingEngine)); section.Diagnostics.Add(new Diagnostic("Enabled Skin Support?", temps.EnableSkinSupport)); section.Diagnostics.Add(new Diagnostic("Use ASP.NET Master Pages?", temps.UseAspNetMasterPages)); sections.Add(section); var wr = UmbracoConfig.For.UmbracoSettings().WebRouting; section = new DiagnosticSection("Web Routing"); section.Diagnostics.Add(new Diagnostic("Disable Alternative Templates?", wr.DisableAlternativeTemplates)); section.Diagnostics.Add(new Diagnostic("Disable Find Content By Id Path?", wr.DisableFindContentByIdPath)); section.Diagnostics.Add(new Diagnostic("Internal Redirect Preserves Template?", wr.InternalRedirectPreservesTemplate)); section.Diagnostics.Add(new Diagnostic("Try Skip IIS Custom Errors?", wr.TrySkipIisCustomErrors)); section.Diagnostics.Add(new Diagnostic("Umbraco Application URL", wr.UmbracoApplicationUrl)); section.Diagnostics.Add(new Diagnostic("URL Provider Mode", wr.UrlProviderMode)); sections.Add(section); section = new DiagnosticSection("Registered Content Finders"); foreach (var item in ContentFinderResolver.Current.Finders) { var t = item.GetType(); section.Diagnostics.Add(new Diagnostic(t.Name, t.GetFullNameWithAssembly())); } sections.Add(section); section = new DiagnosticSection("Registered URL Resolvers"); foreach (var item in UrlProviderResolver.Current.Providers) { var t = item.GetType(); section.Diagnostics.Add(new Diagnostic(t.Name, t.GetFullNameWithAssembly())); } sections.Add(section); var br = UmbracoConfig.For.BaseRestExtensions(); section = new DiagnosticSection("Base Rest Extensions"); section.Diagnostics.Add(new Diagnostic("Enabled?", br.Enabled)); foreach (var item in br.Items) { section.Diagnostics.Add(new Diagnostic(item.Alias, item.Type)); } sections.Add(section); try { var mvc = Assembly.Load(new AssemblyName("Examine")); var name = mvc.GetName(); section = new DiagnosticSection("Examine Settings"); section.Diagnostics.Add(new Diagnostic("Assembly Version", name.Version)); section.Diagnostics.Add(new Diagnostic("Full Name", mvc.FullName)); if (Examine.ExamineManager.Instance != null) { foreach (var provider in Examine.ExamineManager.Instance.IndexProviderCollection) { var p = provider as ProviderBase; if (p != null) { section.Diagnostics.Add(new Diagnostic(p.Name, p.GetType().FullName)); } var l = provider as LuceneIndexer; if (l != null) { section.Diagnostics.Add(new Diagnostic(l.IndexSetName, l.LuceneIndexFolder)); } } foreach (ProviderBase p in Examine.ExamineManager.Instance.SearchProviderCollection) { section.Diagnostics.Add(new Diagnostic(p.Name, p.GetType().FullName)); } section.Diagnostics.Add(new Diagnostic("Default Searcher", Examine.ExamineManager.Instance.DefaultSearchProvider.Name)); } var types = ReflectionHelper.GetTypesAssignableFrom(typeof(UmbracoExamine.LocalStorage.ILocalStorageDirectory)); section.Diagnostics.Add(new Diagnostic("Storage Handlers", String.Join(", ", types.Select(t => t.Name)))); sections.Add(section); } catch { // deliberate } var domains = umbContext.Application.Services.DomainService.GetAll(true); if (domains != null && domains.Any()) { section = new DiagnosticSection("Registered Domains"); foreach (var d in domains) { section.Diagnostics.Add(new Diagnostic(d.LanguageIsoCode, d.DomainName + (d.IsWildcard ? " (Wildcard)" : String.Empty))); } sections.Add(section); } section = new DiagnosticSection("Supported Cultures"); var cultures = umbContext.Application.Services.TextService.GetSupportedCultures(); foreach (var c in cultures) { section.Diagnostics.Add(new Diagnostic(c.ThreeLetterISOLanguageName + " (" + c.TwoLetterISOLanguageName + ")", c.DisplayName)); } sections.Add(section); group.Add(sections); groups.Add(group); group = new DiagnosticGroup(id++, "Server Configuration"); sections = new List <DiagnosticSection>(); section = new DiagnosticSection("Server Settings"); section.Diagnostics.Add(new Diagnostic("Machine Name", Environment.MachineName)); section.Diagnostics.Add(new Diagnostic("OS Version", Environment.OSVersion)); section.Diagnostics.Add(new Diagnostic("64 Bit OS?", Environment.Is64BitOperatingSystem)); section.Diagnostics.Add(new Diagnostic("Processor Count", Environment.ProcessorCount)); section.Diagnostics.Add(new Diagnostic("Network Domain", Environment.UserDomainName)); section.Diagnostics.Add(new Diagnostic("ASP.NET Version", Environment.Version)); if (httpContext != null && httpContext.Request != null) { var request = umbContext.HttpContext.Request; if (request != null) { section.Diagnostics.Add(new Diagnostic("Web Server", request["SERVER_SOFTWARE"])); section.Diagnostics.Add(new Diagnostic("Host", request["HTTP_HOST"])); section.Diagnostics.Add(new Diagnostic("App Pool ID", request["APP_POOL_ID"])); } } section.Diagnostics.Add(new Diagnostic("Current Directory", Environment.CurrentDirectory)); section.Diagnostics.Add(new Diagnostic("64 Bit Process?", Environment.Is64BitProcess)); section.Diagnostics.Add(new Diagnostic("Framework Bits", IntPtr.Size * 8)); section.Diagnostics.Add(new Diagnostic("Process Physical Memory", String.Format("{0:n} MB", Environment.WorkingSet / 1048576))); try { object currentProcess = typeof(Process).GetMethod("GetCurrentProcess", Type.EmptyTypes).Invoke(null, null); if (currentProcess != null) { object processModule = typeof(Process).GetProperty("MainModule").GetValue(currentProcess, null); section.Diagnostics.Add(new Diagnostic("Current Process", (string)typeof(ProcessModule).GetProperty("ModuleName").GetValue(processModule, null))); } } catch { // deliberate } section.Diagnostics.Add(new Diagnostic("Current Culture", System.Threading.Thread.CurrentThread.CurrentCulture)); section.Diagnostics.Add(new Diagnostic("Current Thread State", System.Threading.Thread.CurrentThread.ThreadState)); sections.Add(section); section = new DiagnosticSection("Application Settings"); section.Diagnostics.Add(new Diagnostic("Application ID", HostingEnvironment.ApplicationID)); section.Diagnostics.Add(new Diagnostic("Site Name", HostingEnvironment.SiteName)); section.Diagnostics.Add(new Diagnostic("Development Env?", HostingEnvironment.IsDevelopmentEnvironment)); section.Diagnostics.Add(new Diagnostic("On UNC Share?", HttpRuntime.IsOnUNCShare)); section.Diagnostics.Add(new Diagnostic("Bin Directory", HttpRuntime.BinDirectory)); section.Diagnostics.Add(new Diagnostic("Code Gen Dir", HttpRuntime.CodegenDir)); section.Diagnostics.Add(new Diagnostic("Target Framework", HttpRuntime.TargetFramework)); section.Diagnostics.Add(new Diagnostic("App Domain ID", HttpRuntime.AppDomainId)); section.Diagnostics.Add(new Diagnostic("App Domain Path", HttpRuntime.AppDomainAppPath)); if (HostingEnvironment.Cache != null) { section.Diagnostics.Add(new Diagnostic("Cached Items", HostingEnvironment.Cache.Count.ToString())); section.Diagnostics.Add(new Diagnostic("Cache Memory Limit ", HostingEnvironment.Cache.EffectivePercentagePhysicalMemoryLimit + "%")); } sections.Add(section); if (httpContext != null && httpContext.Request != null) { section = new DiagnosticSection("Server Variables"); section.AddDiagnostics(httpContext.Request.ServerVariables, true, key => !ServerVarsToSkip.Contains(key)); } sections.Add(section); section = new DiagnosticSection("Site Diagnostics"); sections.Add(section); section = new DiagnosticSection("Database Settings"); var dbc = umbContext.Application.DatabaseContext; section.Diagnostics.Add(new Diagnostic("Database Provider", dbc.DatabaseProvider)); section.Diagnostics.Add(new Diagnostic("Connection String", Regex.Replace(dbc.ConnectionString, @"password(\W*)=(.+)(;|$)", "*******", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase))); sections.Add(section); section = new DiagnosticSection("None Umbraco App Settings"); section.AddDiagnostics(ConfigurationManager.AppSettings, false, key => !key.StartsWith("umbraco", StringComparison.OrdinalIgnoreCase)); sections.Add(section); group.Add(sections); groups.Add(group); group = new DiagnosticGroup(id++, "MVC Configuration"); sections = new List <DiagnosticSection>(); try { var mvc = Assembly.Load(new AssemblyName("System.Web.Mvc")); var name = mvc.GetName(); section = new DiagnosticSection("MVC Version"); section.Diagnostics.Add(new Diagnostic("MVC Version", name.Version)); section.Diagnostics.Add(new Diagnostic("Full Name", mvc.FullName)); section.Diagnostics.Add(new Diagnostic("Architecture", name.ProcessorArchitecture)); sections.Add(section); } catch { // deliberate } section = new DiagnosticSection("MVC Routes"); section.Diagnostics.AddRange(RouteTable.Routes.Select(r => (Route)r).Select(r => new Diagnostic(r.RouteHandler.GetType().Name, r.Url))); sections.Add(section); section = new DiagnosticSection("MVC Action Filters"); section.AddDiagnosticsFrom(typeof(System.Web.Mvc.IActionFilter)); sections.Add(section); section = new DiagnosticSection("MVC Authorization Filters"); section.AddDiagnosticsFrom(typeof(System.Web.Mvc.IAuthorizationFilter)); sections.Add(section); section = new DiagnosticSection("MVC Model Binders"); section.AddDiagnosticsFrom(typeof(System.Web.Mvc.IModelBinder)); sections.Add(section); section = new DiagnosticSection("MVC Controller Factories"); section.AddDiagnosticsFrom(typeof(System.Web.Mvc.IControllerFactory)); sections.Add(section); section = new DiagnosticSection("MVC Controllers"); section.AddDiagnosticsFrom(typeof(IController)); sections.Add(section); group.Add(sections); groups.Add(group); return(groups); }
IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) { if (typeof(UmbracoApiControllerBase).IsAssignableFrom(controllerType)) { var owinContext = request.GetOwinContext(); var mockedUserService = Mock.Of <IUserService>(); var mockedContentService = Mock.Of <IContentService>(); var mockedMediaService = Mock.Of <IMediaService>(); var mockedEntityService = Mock.Of <IEntityService>(); var mockedMemberService = Mock.Of <IMemberService>(); var mockedMemberTypeService = Mock.Of <IMemberTypeService>(); var mockedDataTypeService = Mock.Of <IDataTypeService>(); var mockedContentTypeService = Mock.Of <IContentTypeService>(); var mockedMigrationService = new Mock <IMigrationEntryService>(); //set it up to return anything so that the app ctx is 'Configured' mockedMigrationService.Setup(x => x.FindEntry(It.IsAny <string>(), It.IsAny <SemVersion>())).Returns(Mock.Of <IMigrationEntry>()); var serviceContext = new ServiceContext( userService: mockedUserService, contentService: mockedContentService, mediaService: mockedMediaService, entityService: mockedEntityService, memberService: mockedMemberService, memberTypeService: mockedMemberTypeService, dataTypeService: mockedDataTypeService, contentTypeService: mockedContentTypeService, migrationEntryService: mockedMigrationService.Object, localizedTextService: Mock.Of <ILocalizedTextService>(), sectionService: Mock.Of <ISectionService>()); //ensure the configuration matches the current version for tests SettingsForTests.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString(); //new app context var dbCtx = new Mock <DatabaseContext>(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), Mock.Of <ISqlSyntaxProvider>(), "test"); //ensure these are set so that the appctx is 'Configured' dbCtx.Setup(x => x.CanConnect).Returns(true); dbCtx.Setup(x => x.IsDatabaseConfigured).Returns(true); var appCtx = ApplicationContext.EnsureContext( dbCtx.Object, //pass in mocked services serviceContext, CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()), true); //httpcontext with an auth'd user var httpContext = Mock.Of <HttpContextBase>( http => http.User == owinContext.Authentication.User //ensure the request exists with a cookies collection && http.Request == Mock.Of <HttpRequestBase>(r => r.Cookies == new HttpCookieCollection()) //ensure the request exists with an items collection && http.Items == Mock.Of <IDictionary>()); //chuck it into the props since this is what MS does when hosted and it's needed there request.Properties["MS_HttpContext"] = httpContext; var backofficeIdentity = (UmbracoBackOfficeIdentity)owinContext.Authentication.User.Identity; var webSecurity = new Mock <WebSecurity>(null, null); //mock CurrentUser var groups = new List <ReadOnlyUserGroup>(); for (var index = 0; index < backofficeIdentity.Roles.Length; index++) { var role = backofficeIdentity.Roles[index]; groups.Add(new ReadOnlyUserGroup(index + 1, role, "icon-user", null, null, role, new string[0], new string[0])); } webSecurity.Setup(x => x.CurrentUser) .Returns(Mock.Of <IUser>(u => u.IsApproved == true && u.IsLockedOut == false && u.AllowedSections == backofficeIdentity.AllowedApplications && u.Groups == groups && u.Email == "*****@*****.**" && u.Id == (int)backofficeIdentity.Id && u.Language == "en" && u.Name == backofficeIdentity.RealName && u.StartContentIds == backofficeIdentity.StartContentNodes && u.StartMediaIds == backofficeIdentity.StartMediaNodes && u.Username == backofficeIdentity.Username)); //mock Validate webSecurity.Setup(x => x.ValidateCurrentUser()) .Returns(() => true); webSecurity.Setup(x => x.UserHasSectionAccess(It.IsAny <string>(), It.IsAny <IUser>())) .Returns(() => true); var umbCtx = UmbracoContext.EnsureContext( //set the user of the HttpContext httpContext, appCtx, webSecurity.Object, Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == UrlProviderMode.Auto.ToString())), Enumerable.Empty <IUrlProvider>(), true); //replace it var urlHelper = new Mock <IUrlProvider>(); urlHelper.Setup(provider => provider.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <int>(), It.IsAny <Uri>(), It.IsAny <UrlProviderMode>())) .Returns("/hello/world/1234"); var membershipHelper = new MembershipHelper(umbCtx, Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>()); var mockedTypedContent = Mock.Of <ITypedPublishedContentQuery>(); var umbHelper = new UmbracoHelper(umbCtx, Mock.Of <IPublishedContent>(), mockedTypedContent, Mock.Of <IDynamicPublishedContentQuery>(), Mock.Of <ITagQuery>(), Mock.Of <IDataTypeService>(), new UrlProvider(umbCtx, new[] { urlHelper.Object }, UrlProviderMode.Auto), Mock.Of <ICultureDictionary>(), Mock.Of <IUmbracoComponentRenderer>(), membershipHelper); return(CreateController(controllerType, request, umbHelper)); } //default return(base.Create(request, controllerDescriptor, controllerType)); }
public void Is_Version_From_Assembly_Correct() { Assert.That(UmbracoVersion.GetSemanticVersion(), Is.EqualTo("6.0.0")); }
/// <summary> /// This assumes all of the previous checks are done! /// </summary> /// <returns></returns> internal Result UpgradeSchemaAndData(IMigrationEntryService migrationEntryService) { try { var readyForInstall = CheckReadyForInstall(); if (readyForInstall.Success == false) { return(readyForInstall.Result); } _logger.Info <DatabaseContext>("Database upgrade started"); var database = new UmbracoDatabase(_connectionString, ProviderName, _logger); //var supportsCaseInsensitiveQueries = SqlSyntax.SupportsCaseInsensitiveQueries(database); var message = GetResultMessageForMySql(); var schemaResult = ValidateDatabaseSchema(); var installedSchemaVersion = new SemVersion(schemaResult.DetermineInstalledVersion()); var installedMigrationVersion = schemaResult.DetermineInstalledVersionByMigrations(migrationEntryService); var targetVersion = UmbracoVersion.Current; //In some cases - like upgrading from 7.2.6 -> 7.3, there will be no migration information in the database and therefore it will // return a version of 0.0.0 and we don't necessarily want to run all migrations from 0 -> 7.3, so we'll just ensure that the // migrations are run for the target version if (installedMigrationVersion == new SemVersion(new Version(0, 0, 0)) && installedSchemaVersion > new SemVersion(new Version(0, 0, 0))) { //set the installedMigrationVersion to be one less than the target so the latest migrations are guaranteed to execute installedMigrationVersion = new SemVersion(targetVersion.SubtractRevision()); } //Figure out what our current installed version is. If the web.config doesn't have a version listed, then we'll use the minimum // version detected between the schema installed and the migrations listed in the migration table. // If there is a version in the web.config, we'll take the minimum between the listed migration in the db and what // is declared in the web.config. var currentInstalledVersion = string.IsNullOrEmpty(GlobalSettings.ConfigurationStatus) //Take the minimum version between the detected schema version and the installed migration version ? new[] { installedSchemaVersion, installedMigrationVersion }.Min() //Take the minimum version between the installed migration version and the version specified in the config : new[] { SemVersion.Parse(GlobalSettings.ConfigurationStatus), installedMigrationVersion }.Min(); //Ok, another edge case here. If the current version is a pre-release, // then we want to ensure all migrations for the current release are executed. if (currentInstalledVersion.Prerelease.IsNullOrWhiteSpace() == false) { currentInstalledVersion = new SemVersion(currentInstalledVersion.GetVersion().SubtractRevision()); } //DO the upgrade! var runner = new MigrationRunner(migrationEntryService, _logger, currentInstalledVersion, UmbracoVersion.GetSemanticVersion(), Constants.System.UmbracoMigrationName); var upgraded = runner.Execute(database, true); if (upgraded == false) { throw new ApplicationException("Upgrading failed, either an error occurred during the upgrade process or an event canceled the upgrade process, see log for full details"); } message = message + "<p>Upgrade completed!</p>"; //now that everything is done, we need to determine the version of SQL server that is executing _logger.Info <DatabaseContext>("Database configuration status: " + message); return(new Result { Message = message, Success = true, Percentage = "100" }); } catch (Exception ex) { return(HandleInstallException(ex)); } }
public virtual IBootManager Initialize() { if (_isInitialized) { throw new InvalidOperationException("The boot manager has already been initialized"); } InitializeLoggerResolver(); InitializeProfilerResolver(); ProfilingLogger = ProfilingLogger ?? new ProfilingLogger(LoggerResolver.Current.Logger, ProfilerResolver.Current.Profiler); _timer = ProfilingLogger.TraceDuration <CoreBootManager>( string.Format("Umbraco {0} application starting on {1}", UmbracoVersion.GetSemanticVersion().ToSemanticString(), NetworkHelper.MachineName), "Umbraco application startup complete"); ApplicationCache = CreateApplicationCache(); //create and set the plugin manager (I'd much prefer to not use this singleton anymore but many things are using it unfortunately and // the way that it is setup, there must only ever be one per app so without IoC it would be hard to make this not a singleton) PluginManager = new PluginManager(ServiceProvider, ApplicationCache.RuntimeCache, ProfilingLogger); PluginManager.Current = PluginManager; //Create the legacy prop-eds mapping LegacyPropertyEditorIdToAliasConverter.CreateMappingsForCoreEditors(); LegacyParameterEditorAliasConverter.CreateMappingsForCoreEditors(); //create database and service contexts for the app context var dbFactory = new DefaultDatabaseFactory(Constants.System.UmbracoConnectionName, ProfilingLogger.Logger); Database.Mapper = new PetaPocoMapper(); var scopeProvider = new ScopeProvider(dbFactory); dbFactory.ScopeProvider = scopeProvider; var dbContext = new DatabaseContext( scopeProvider, ProfilingLogger.Logger, SqlSyntaxProviders.CreateDefault(ProfilingLogger.Logger)); //initialize the DatabaseContext dbContext.Initialize(); //get the service context var serviceContext = CreateServiceContext(dbContext, scopeProvider); //set property and singleton from response ApplicationContext.Current = ApplicationContext = CreateApplicationContext(dbContext, serviceContext); InitializeApplicationEventsResolver(); InitializeResolvers(); InitializeModelMappers(); using (ProfilingLogger.DebugDuration <CoreBootManager>( string.Format("Executing {0} IApplicationEventHandler.OnApplicationInitialized", ApplicationEventsResolver.Current.ApplicationEventHandlers.Count()), "Finished executing IApplicationEventHandler.OnApplicationInitialized")) { //now we need to call the initialize methods ApplicationEventsResolver.Current.ApplicationEventHandlers .ForEach(x => { try { using (ProfilingLogger.DebugDuration <CoreBootManager>(string.Format("Executing {0} in ApplicationInitialized", x.GetType()))) { x.OnApplicationInitialized(UmbracoApplication, ApplicationContext); } } catch (Exception ex) { ProfilingLogger.Logger.Error <CoreBootManager>("An error occurred running OnApplicationInitialized for handler " + x.GetType(), ex); throw; } }); } _isInitialized = true; return(this); }