コード例 #1
0
        /// <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("cacheBuster", string.Format("{0}.{1}", version, 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);
        }
コード例 #2
0
        public void ProcessRequest(HttpContext context)
        {
            //TODO: Authorize this request!!!

            var file           = context.Request.Files["Filedata"];
            var userguid       = context.Request.Form["USERGUID"];
            var nodeguid       = context.Request.Form["NODEGUID"];
            var fileType       = context.Request.Form["FILETYPE"];
            var fileName       = context.Request.Form["FILENAME"];
            var umbracoVersion = context.Request.Form["UMBRACOVERSION"];

            var versions = new List <UmbracoVersion> {
                UmbracoVersion.DefaultVersion()
            };

            if (string.IsNullOrWhiteSpace(umbracoVersion) == false)
            {
                versions.Clear();
                versions = WikiFile.GetVersionsFromString(umbracoVersion);
            }

            if (string.IsNullOrWhiteSpace(userguid) == false &&
                string.IsNullOrWhiteSpace(nodeguid) == false &&
                string.IsNullOrWhiteSpace(fileType) == false &&
                string.IsNullOrWhiteSpace(fileName) == false)
            {
                WikiFile.Create(fileName, new Guid(nodeguid), new Guid(userguid), file, fileType, versions);
            }
        }
コード例 #3
0
        public override InstallSetupResult Execute(object model)
        {
            var ih = new InstallHelper(UmbracoContext.Current);

            //During a new install we'll log the default user in (which is id = 0).
            // During an upgrade, the user will already need to be logged in in order to run the installer.

            var security = new WebSecurity(_httpContext, _applicationContext);

            //we do this check here because for upgrades the user will already be logged in, for brand new installs,
            // they will not be logged in, however we cannot check the current installation status because it will tell
            // us that it is in 'upgrade' because we already have a database conn configured and a database.
            if (security.IsAuthenticated() == false && GlobalSettings.ConfigurationStatus.IsNullOrWhiteSpace())
            {
                security.PerformLogin(0);
            }

            //This is synonymous with library.RefreshContent() - but we don't want to use library
            // for anything anymore so welll use the method that it is wrapping. This will just make sure
            // the correct xml structure exists in the xml cache file. This is required by some upgrade scripts
            // that may modify the cmsContentXml table directly.
            DistributedCache.Instance.RefreshAllPageCache();

            // Update configurationStatus
            GlobalSettings.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString();

            //reports the ended install
            ih.InstallStatus(true, "");

            return(null);
        }
        /// <summary>
        /// Outputs a script tag containing the bare minimum (non secure) server vars for use with the angular app
        /// </summary>
        /// <param name="html"></param>
        /// <param name="uri"></param>
        /// <param name="externalLoginsUrl">
        /// The post url used to sign in with external logins - this can change depending on for what service the external login is service.
        /// Example: normal back office login or authenticating upgrade login
        /// </param>
        /// <returns></returns>
        /// <remarks>
        /// These are the bare minimal server variables that are required for the application to start without being authenticated,
        /// we will load the rest of the server vars after the user is authenticated.
        /// </remarks>
        public static IHtmlString BareMinimumServerVariablesScript(this HtmlHelper html, UrlHelper uri, string externalLoginsUrl)
        {
            var version = UmbracoVersion.GetSemanticVersion().ToSemanticString();
            var str     = @"<script type=""text/javascript"">
                var Umbraco = {};
                Umbraco.Sys = {};
                Umbraco.Sys.ServerVariables = {
                    ""umbracoUrls"": {
                        ""authenticationApiBaseUrl"": """ + uri.GetUmbracoApiServiceBaseUrl <AuthenticationController>(controller => controller.PostLogin(null)) + @""",
                        ""serverVarsJs"": """ + uri.GetUrlWithCacheBust("ServerVariables", "BackOffice") + @""",
                        ""externalLoginsUrl"": """ + externalLoginsUrl + @"""
                    },
                    ""umbracoSettings"": {
                        ""allowPasswordReset"": " + (UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset ? "true" : "false") + @",
                        ""loginBackgroundImage"": """ + UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage + @"""
                    },
                    ""application"": {
                        ""applicationPath"": """ + html.ViewContext.HttpContext.Request.ApplicationPath + @""",
                        ""cacheBuster"": """ + string.Format("{0}.{1}", version, ClientDependencySettings.Instance.Version).GenerateHash() + @"""
                    },
                    ""isDebuggingEnabled"" : " + html.ViewContext.HttpContext.IsDebuggingEnabled.ToString().ToLowerInvariant() + @"
                };       
            </script>";

            return(html.Raw(str));
        }
        /// <summary>
        /// check to see if the Umbraco local temp location has been set by an app setting
        /// </summary>
        /// <returns></returns>
        private HealthCheckStatus DisplayUmbracoLocalTempStorage()
        {
            var resultMessage           = "Umbraco local temporary location hasn't been set by an app setting, default \"~/App_Data/ location is in use";
            StatusResultType resultType = StatusResultType.Info;
            // can we fix anything
            var actions = new List <HealthCheckAction>();
            var currentUmbracoVersion = UmbracoVersion.GetSemanticVersion();

            var tempSettings = new List <string>();

            if (ConfigurationManager.AppSettings.ContainsKey("umbracoLocalTempStorage"))
            {
                tempSettings.Add("umbracoLocalTempStorage");
                var umbracoLocalTempStorage = ConfigurationManager.AppSettings["umbracoLocalTempStorage"];
                resultMessage =
                    $"Umbraco local temporary location is set to {umbracoLocalTempStorage} using the umbracoLocalTempStorage app setting";
            }

            if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLStorage"))
            {
                tempSettings.Add("umbracoContentXMLStorage");
                var umbracoContentXMLStorage = ConfigurationManager.AppSettings["umbracoContentXMLStorage"];
                resultMessage = $"Umbraco local temporary location is set to {umbracoContentXMLStorage} using the umbracoContentXMLStorage app setting";
                if (currentUmbracoVersion >= new SemVersion(7, 7, 3))
                {
                    resultMessage = $"{resultMessage}, it is recommended that you change to using umbracoLocalTempStorage";
                    resultType    = StatusResultType.Warning;
                }
            }
            if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp"))
            {
                tempSettings.Add("umbracoContentXMLUseLocalTemp");
                var umbracoContentXMLUseLocalTemp = ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"];
                resultMessage = $"Umbraco local temporary location is set to {umbracoContentXMLUseLocalTemp} using the umbracoContentXMLStorage app setting";
                if (currentUmbracoVersion >= new SemVersion(7, 7, 3))
                {
                    resultMessage = $"{resultMessage}, it is recommended that you change to using umbracoLocalTempStorage";
                    resultType    = StatusResultType.Warning;
                }
                else if (currentUmbracoVersion >= new SemVersion(7, 6))
                {
                    resultMessage = $"{resultMessage}, it is recommended that you change to using umbracoContentXMLStorage";
                    resultType    = StatusResultType.Warning;
                }
            }

            // check for multiple temp location settings, this will override all above checks
            if (tempSettings.Count > 1)
            {
                resultMessage = $"Multiple Umbraco local temporary settings are in use, there should be only one! {string.Join(", ", tempSettings.ToArray())} found to be in use";
                resultType    = StatusResultType.Error;
            }

            return
                (new HealthCheckStatus(resultMessage)
            {
                ResultType = resultType,
                Actions = actions
            });
        }
コード例 #6
0
        public WikiFile CreateFile(string fileName, Guid listingVersionGuid, Guid vendorGuid, HttpPostedFile file, FileType fileType, List <UmbracoVersion> v, string dotNetVersion, bool mediumTrust)
        {
            // we have to convert to the uWiki UmbracoVersion :(

            List <UmbracoVersion> vers = new List <UmbracoVersion>();

            foreach (var ver in v)
            {
                vers.Add(UmbracoVersion.AvailableVersions()[ver.Version]);
            }


            //Create the Wiki File
            var uWikiFile = WikiFile.Create(fileName, listingVersionGuid, vendorGuid, file, GetFileTypeAsString(fileType), vers);
            //return the IMediaFile

            //Convert to Deli Media file
            var mediaFile = GetFileById(uWikiFile.Id);

            mediaFile.SetMinimumUmbracoVersion();

            mediaFile.DotNetVersion = dotNetVersion;
            SaveOrUpdate(mediaFile);
            return(mediaFile);
        }
コード例 #7
0
        public override void Initialize()
        {
            InitializeFirstRunFlags();

            var path = TestHelper.CurrentAssemblyDirectory;

            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            _dbFactory = new Umbraco.Core.Persistence.DefaultDatabaseFactory(
                GetDbConnectionString(),
                GetDbProviderName(),
                Logger);
            //_dbFactory.ResetForTests();

            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();
            }
        }
コード例 #8
0
        public override InstallSetupResult Execute(object model)
        {
            //This is synonymous with library.RefreshContent() - but we don't want to use library
            // for anything anymore so welll use the method that it is wrapping. This will just make sure
            // the correct xml structure exists in the xml cache file. This is required by some upgrade scripts
            // that may modify the cmsContentXml table directly.
            DistributedCache.Instance.RefreshAllPageCache();

            // Update configurationStatus
            GlobalSettings.ConfigurationStatus = UmbracoVersion.GetSemanticVersion().ToSemanticString();

            // Update ClientDependency version
            var clientDependencyConfig  = new ClientDependencyConfiguration(_applicationContext.ProfilingLogger.Logger);
            var clientDependencyUpdated = clientDependencyConfig.IncreaseVersionNumber();

            var security = new WebSecurity(_httpContext, _applicationContext);

            security.PerformLogin(0);

            //reports the ended install
            var ih = new InstallHelper(UmbracoContext.Current);

            ih.InstallStatus(true, "");

            return(null);
        }
コード例 #9
0
        public static List <UmbracoVersion> GetVersionsFromString(string p)
        {
            var verArray = p.Split(',');
            var verList  = new List <UmbracoVersion>();

            foreach (var ver in verArray)
            {
                verList.Add(UmbracoVersion.AvailableVersions()[ver]);
            }
            return(verList);
        }
コード例 #10
0
        private void CreateUmbracoMigrationData()
        {
            var dto = new MigrationDto
            {
                Id         = 1,
                Name       = Constants.System.UmbracoMigrationName,
                Version    = UmbracoVersion.GetSemanticVersion().ToString(),
                CreateDate = DateTime.Now
            };

            _database.Insert("umbracoMigration", "pk", false, dto);
        }
コード例 #11
0
        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 userType        = user.UserType.Alias;
            var allowedSections = string.Join(",", user.AllowedSections);
            var language        = user.Language;
            var version         = UmbracoVersion.GetSemanticVersion().ToSemanticString();

            var url = string.Format(baseUrl + "{0}?section={0}&type={1}&allowed={2}&lang={3}&version={4}", section, userType, allowedSections, language, version);
            var key = "umbraco-dynamic-dashboard-" + userType + 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
                {
                    using (var web = new HttpClient())
                    {
                        //fetch dashboard json and parse to JObject
                        var json = await web.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);
        }
コード例 #12
0
        public static IList <SelectListItem> GetUmbracoVersions()
        {
            var umbracoVersions = new List <SelectListItem>();

            foreach (var uv in UmbracoVersion.AvailableVersions().Values)
            {
                umbracoVersions.Add(new SelectListItem {
                    Text = uv.Name, Value = uv.Version
                });
            }

            return(umbracoVersions);
        }
コード例 #13
0
        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);
                }
            });
        }
コード例 #14
0
        /// <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());
        }
コード例 #15
0
        public void ProcessRequest(HttpContext context)
        {
            //TODO: Authorize this request!!!

            HttpPostedFile file          = context.Request.Files["Filedata"];
            string         userguid      = context.Request.Form["USERGUID"];
            string         nodeguid      = context.Request.Form["NODEGUID"];
            string         fileType      = context.Request.Form["FILETYPE"];
            string         fileName      = context.Request.Form["FILENAME"];
            string         umbraoVersion = context.Request.Form["UMBRACOVERSION"];
            string         dotNetVersion = context.Request.Form["DOTNETVERSION"];

            List <UmbracoVersion> v = new List <UmbracoVersion>()
            {
                UmbracoVersion.DefaultVersion()
            };

            if (!string.IsNullOrEmpty(umbraoVersion))
            {
                v.Clear();
                v = WikiFile.GetVersionsFromString(umbraoVersion);
            }

            if (!string.IsNullOrEmpty(userguid) && !string.IsNullOrEmpty(nodeguid) && !string.IsNullOrEmpty(fileType) && !string.IsNullOrEmpty(fileName))
            {
                Document d   = new Document(Document.GetContentFromVersion(new Guid(nodeguid)).Id);
                Member   mem = new Member(new Guid(userguid));

                if (d.ContentType.Alias == "Project" && d.getProperty("owner") != null && (d.getProperty("owner").Value.ToString() == mem.Id.ToString() || Utils.IsProjectContributor(mem.Id, d.Id)))
                {
                    WikiFile.Create(fileName, new Guid(nodeguid), new Guid(userguid), file, fileType, v, dotNetVersion);

                    //the package publish handler will make sure we got the right versions info on the package node itself.
                    //ProjectsEnsureGuid.cs is the handler
                    if (fileType.ToLower() == "package")
                    {
                        d.Publish(new umbraco.BusinessLogic.User(0));
                        umbraco.library.UpdateDocumentCache(d.Id);
                    }
                }
                else
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, 0, "wrong type or not a owner");
                }
            }
        }
コード例 #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (library.IsLoggedOn() && ProjectId != null)
            {
                var          nodeListingProvider = new NodeListingProvider();
                Member       mem     = Member.GetCurrentMember();
                IListingItem project = nodeListingProvider.GetListing((int)ProjectId);
                _defaultFile = project.CurrentReleaseFile;



                if ((project.VendorId == mem.Id) ||
                    Utils.IsProjectContributor(mem.Id, (int)ProjectId))
                {
                    holder.Visible = true;
                    RebindFiles();

                    library.RegisterJavaScriptFile("swfUpload", "/scripts/swfupload/SWFUpload.js");
                    library.RegisterJavaScriptFile("swfUpload_cb", "/scripts/swfupload/callbacks.js");
                    library.RegisterJavaScriptFile("swfUpload_progress", "/scripts/swfupload/fileprogress.js");

                    MemberGuid  = mem.UniqueId.ToString();
                    ProjectGuid = project.ProjectGuid.ToString();

                    string umboptions = "";

                    foreach (UmbracoVersion uv in UmbracoVersion.AvailableVersions().Values)
                    {
                        umboptions += string.Format("<input type='checkbox' name='wiki_version' value='{0}' /><span> {1}</span></br>", uv.Version, uv.Name);
                    }

                    lt_versions.Text = umboptions;


                    string[] dotnetversions = { "", "2.0", "3.5", "4.0", "4.5" };
                    string   dotnetoptions  = string.Empty;

                    foreach (var opt in dotnetversions)
                    {
                        dotnetoptions += string.Format("<option value='{0}'>{1}</option>", opt, opt);
                    }

                    lt_dotnetversions.Text = dotnetoptions;
                }
            }
        }
コード例 #17
0
        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);
        }
コード例 #18
0
        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();
            }
        }
コード例 #19
0
        public ActionResult AddFile(EditFileModel model)
        {
            if (ModelState.IsValid == false)
            {
                return(CurrentUmbracoPage());
            }

            // Getting this despite not using it to verify that the member owns this file
            var project = GetProjectForAuthorizedMember(model.UploadFile.ProjectId);
            var member  = Members.GetCurrentMember();

            HttpPostedFile file;

            using (var target = new MemoryStream())
            {
                model.UploadFile.File.InputStream.CopyTo(target);
                byte[] data = target.ToArray();
                file = ConstructHttpPostedFile(data, model.UploadFile.File.FileName, model.UploadFile.File.ContentType);
            }

            var umbracoVersions    = new List <UmbracoVersion>();
            var allUmbracoVersions = UmbracoVersion.AvailableVersions().Values;

            foreach (var item in model.UploadFile.SelectedVersions)
            {
                var version = allUmbracoVersions.Single(x => x.Version == item);
                umbracoVersions.Add(version);
            }

            var contentService = Services.ContentService;
            var projectContent = contentService.GetById(project.Id);

            var wikiFile = WikiFile.Create(
                model.UploadFile.File.FileName,
                projectContent.PublishedVersionGuid,
                member.GetKey(),
                file,
                model.UploadFile.FileType,
                umbracoVersions,
                model.UploadFile.DotNetVersion
                );

            return(RedirectToCurrentUmbracoPage(Request.Url.Query));
        }
コード例 #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (umbraco.library.IsLoggedOn())
            {
                pageId = umbraco.presentation.nodeFactory.Node.GetCurrent().Id;


                Member   mem = Member.GetCurrentMember();
                Document d   = new Document(pageId);

                //if (n.GetProperty("owner") != null && n.GetProperty("owner").Value == mem.Id.ToString())
                //{
                holder.Visible = true;
                RebindFiles();

                umbraco.library.RegisterJavaScriptFile("swfUpload", "/scripts/swfupload/SWFUpload.js");
                umbraco.library.RegisterJavaScriptFile("swfUpload_cb", "/scripts/swfupload/callbacks.js");
                umbraco.library.RegisterJavaScriptFile("swfUpload_progress", "/scripts/swfupload/fileprogress.js");

                MemberGuid  = mem.UniqueId.ToString();
                VersionGuid = d.Version.ToString();

                string defaultVersion = UmbracoVersion.DefaultVersion().Version;
                string options        = "";

                foreach (UmbracoVersion uv in UmbracoVersion.AvailableVersions().Values)
                {
                    string selected = "selected='true'";
                    if (uv.Version != defaultVersion)
                    {
                        selected = "";
                    }
                    options += string.Format("<option value='{0}' {2}>{1}</option>", uv.Version, uv.Name, selected);
                }

                lt_versions.Text = options;
                //}
            }
            else
            {
                notLoggedIn.Visible = true;
            }
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        /// <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);
        }
コード例 #23
0
        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();
            }
        }
コード例 #24
0
        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"));
        }
コード例 #25
0
        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);
        }
コード例 #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (umbraco.library.IsLoggedOn() && int.TryParse(Request.QueryString["id"], out pageId))
            {
                Member   mem = Member.GetCurrentMember();
                Document d   = new Document(pageId);

                if ((d.getProperty("owner") != null && d.getProperty("owner").Value.ToString() == mem.Id.ToString()) ||
                    Utils.IsProjectContributor(mem.Id, pageId))
                {
                    holder.Visible = true;
                    RebindFiles();

                    umbraco.library.RegisterJavaScriptFile("swfUpload", "/scripts/swfupload/SWFUpload.js");
                    umbraco.library.RegisterJavaScriptFile("swfUpload_cb", "/scripts/swfupload/callbacks.js");
                    umbraco.library.RegisterJavaScriptFile("swfUpload_progress", "/scripts/swfupload/fileprogress.js");

                    MemberGuid  = mem.UniqueId.ToString();
                    VersionGuid = d.Version.ToString();

                    string defaultVersion = UmbracoVersion.DefaultVersion().Version;
                    string options        = "";

                    foreach (UmbracoVersion uv in UmbracoVersion.AvailableVersions().Values)
                    {
                        string selected = "selected='true'";
                        if (uv.Version != defaultVersion)
                        {
                            selected = "";
                        }
                        options += string.Format("<option value='{0}' {2}>{1}</option>", uv.Version, uv.Name, selected);
                    }

                    lt_versions.Text = options;
                }
            }
        }
コード例 #27
0
        public ActionResult AddScreenshot(EditScreenshotModel model)
        {
            if (ModelState.IsValid == false)
            {
                return(CurrentUmbracoPage());
            }

            // Getting this despite not using it to verify that the member owns this file
            var project = GetProjectForAuthorizedMember(model.UploadFile.ProjectId);
            var member  = Members.GetCurrentMember();

            HttpPostedFile file;

            using (var target = new MemoryStream())
            {
                model.UploadFile.File.InputStream.CopyTo(target);
                byte[] data = target.ToArray();
                file = ConstructHttpPostedFile(data, model.UploadFile.File.FileName, model.UploadFile.File.ContentType);
            }

            var contentService = Services.ContentService;
            var projectContent = contentService.GetById(project.Id);

            var wikiFile = WikiFile.Create(
                model.UploadFile.File.FileName,
                projectContent.PublishedVersionGuid,
                member.GetKey(),
                file,
                "screenshot",
                new List <UmbracoVersion> {
                UmbracoVersion.DefaultVersion()
            }
                );

            return(RedirectToCurrentUmbracoPage(Request.Url.Query));
        }
コード例 #28
0
        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>");
            }
        }
コード例 #29
0
ファイル: DatabaseContext.cs プロジェクト: agrath/Umbraco-CMS
        /// <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));
            }
        }
コード例 #30
0
        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));
        }