Example #1
0
        public void FileSystemConfiguration_GetSiteRootFolders_Includes_Sites_Added_In_Order_Of_Priority()
        {
            var abcFolder = @"c:\web\abc";
            var xyzFolder = @"c:\web\xyz";

            _FileSystemProvider.AddFolder(abcFolder);
            _FileSystemProvider.AddFolder(xyzFolder);

            for (var i = 0; i < 2; ++i)
            {
                var expectAbcFirst = i % 2 == 0;
                var abcSiteRoot    = new SiteRoot()
                {
                    Folder = abcFolder, Priority = expectAbcFirst ? -1 : 1
                };
                var xyzSiteRoot = new SiteRoot()
                {
                    Folder = xyzFolder, Priority = expectAbcFirst ? 1 : -1
                };
                _Configuration.AddSiteRoot(abcSiteRoot);
                _Configuration.AddSiteRoot(xyzSiteRoot);

                var folders = _Configuration.GetSiteRootFolders();
                Assert.AreEqual(2, folders.Count);
                var abcIsFirst = folders[0].ToLower().TrimEnd('\\', '/') == abcFolder.ToLower();

                Assert.AreEqual(expectAbcFirst, abcIsFirst);
                _Configuration.RemoveSiteRoot(abcSiteRoot);
                _Configuration.RemoveSiteRoot(xyzSiteRoot);
            }
        }
Example #2
0
        public void TestInitialise()
        {
            _OriginalFactory = Factory.TakeSnapshot();

            _Extender = Factory.Singleton.Resolve <IWebSiteExtender>();

            _WebSite = TestUtilities.CreateMockInstance <IWebSite>();
            _PluginStartupParameters = new PluginStartupParameters(null, null, _WebSite.Object, "PluginFolder");

            _AddSiteRoot    = null;
            _RemoveSiteRoot = null;
            _WebSite.Setup(r => r.AddSiteRoot(It.IsAny <SiteRoot>())).Callback((SiteRoot siteRoot) => _AddSiteRoot       = siteRoot);
            _WebSite.Setup(r => r.RemoveSiteRoot(It.IsAny <SiteRoot>())).Callback((SiteRoot siteRoot) => _RemoveSiteRoot = siteRoot);

            _AddHtmlContentInjectors    = new List <HtmlContentInjector>();
            _RemoveHtmlContentInjectors = new List <HtmlContentInjector>();
            _WebSite.Setup(r => r.AddHtmlContentInjector(It.IsAny <HtmlContentInjector>())).Callback((HtmlContentInjector injector) => _AddHtmlContentInjectors.Add(injector));
            _WebSite.Setup(r => r.RemoveHtmlContentInjector(It.IsAny <HtmlContentInjector>())).Callback((HtmlContentInjector injector) => _RemoveHtmlContentInjectors.Add(injector));

            _AutoConfigWebServer = TestUtilities.CreateMockSingleton <IAutoConfigWebServer>();
            _WebServer           = TestUtilities.CreateMockInstance <IWebServer>();
            _AutoConfigWebServer.Setup(r => r.WebServer).Returns(_WebServer.Object);
            _Request  = TestUtilities.CreateMockInstance <IRequest>();
            _Response = TestUtilities.CreateMockInstance <IResponse>();
        }
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="siteRoot"></param>
        public void AddSiteRoot(SiteRoot siteRoot)
        {
            var fileSystem = Factory.Singleton.Resolve <IFileSystemProvider>();

            if (siteRoot == null)
            {
                throw new ArgumentNullException(nameof(siteRoot));
            }
            if (String.IsNullOrEmpty(siteRoot.Folder))
            {
                throw new ArgumentException(nameof(siteRoot.Folder));
            }
            if (!fileSystem.DirectoryExists(siteRoot.Folder))
            {
                throw new InvalidOperationException($"{siteRoot.Folder} does not exist");
            }
            if (!Path.IsPathRooted(siteRoot.Folder))
            {
                throw new InvalidOperationException($"{siteRoot.Folder} is a relative path - only absolute paths can be site roots");
            }

            var folder = NormalisePath(siteRoot.Folder);

            if (_Roots.Any(r => r.Folder.Equals(folder, StringComparison.OrdinalIgnoreCase)))
            {
                throw new InvalidOperationException($"{siteRoot.Folder} is already a site root");
            }

            _Roots.Add(new Root(folder, siteRoot));
            _Roots.Sort((lhs, rhs) => { return(lhs.Priority < rhs.Priority ? -1 : lhs.Priority == rhs.Priority ? 0 : 1); });
        }
Example #4
0
		private void SetupReturnUrlCookie()
		{
			if (Page.IsPostBack)
			{ return; }

			string returnUrl = string.Empty;

			if (Page.Request.UrlReferrer != null)
			{
				string urlReferrer = Page.Request.UrlReferrer.ToString();
				if ((urlReferrer.StartsWith(SiteRoot)) || (urlReferrer.StartsWith(SiteRoot.Replace("https://", "http://"))))
				{
					returnUrl = urlReferrer;

				}
			}

			string returnUrlParam = Page.Request.Params.Get("returnurl");

			if (!String.IsNullOrEmpty(returnUrlParam))
			{
				returnUrlParam = SecurityHelper.RemoveMarkup(Page.Server.UrlDecode(returnUrlParam));
				string redirectUrl = Page.ResolveUrl(returnUrlParam);
				if ((redirectUrl.StartsWith(SiteRoot)) || (redirectUrl.StartsWith(SiteRoot.Replace("https://", "http://"))))
				{
					returnUrl = redirectUrl;
				}
			}

			if (returnUrl.Length > 0)
			{ CookieHelper.SetCookie(returnUrlCookieName, returnUrl); }
		}
Example #5
0
        public void SiteRoot_Constructor_Initialises_To_Known_State_And_Properties_Work()
        {
            var instance = new SiteRoot();

            Assert.AreEqual(0, instance.Checksums.Count);
            TestUtilities.TestProperty(instance, r => r.Folder, null, "c:\\whatever");
            TestUtilities.TestProperty(instance, r => r.Priority, 100, -100);
        }
        public static async Task <DiscordEmbedBuilder> GetSimpsonsDataAsync(SiteRoot site)
        {
            var output = await _http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false);

            var results = JsonConvert.DeserializeObject <SimpsonsData>(output);

            return(EmbedSimpsonsEpisode(results, site));
        }
Example #7
0
        public static async Task <DiscordEmbedBuilder> GetSimpsonsDataAsync(SiteRoot site)
        {
            var output = await Http.GetStringAsync(string.Format(Resources.URL_Simpsons_Random, site))
                         .ConfigureAwait(false);

            var results = JsonConvert.DeserializeObject <SimpsonsData>(output);

            return(EmbedSimpsonsEpisode(results, site));
        }
Example #8
0
        public void FileSystemConfiguration_IsSiteRootActive_Returns_False_If_SiteRoot_Not_Added()
        {
            var siteRoot = new SiteRoot()
            {
                Folder = TestContext.TestDeploymentDir
            };

            Assert.IsFalse(_Configuration.IsSiteRootActive(siteRoot, false));
        }
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="siteRoot"></param>
        public void RemoveSiteRoot(SiteRoot siteRoot)
        {
            var root = _Roots.SingleOrDefault(r => r.SiteRoot == siteRoot);

            if (root != null)
            {
                _Roots.Remove(root);
                root.Dispose();
            }
        }
Example #10
0
 private List <TestResults> MapTestResults(SiteRoot r)
 {
     return(r.Tests.Select(t => new TestResults
     {
         TestStart = t.TimeOfTest,
         Urls = MapUrls(t),
     })
            .OrderBy(tr => tr.TestStart)
            .ToList());
 }
            /// <summary>
            /// Creates a new object.
            /// </summary>
            /// <param name="folder"></param>
            /// <param name="siteRoot"></param>
            public Root(string folder, SiteRoot siteRoot)
            {
                SiteRoot = siteRoot;
                Folder   = folder;
                Priority = siteRoot.Priority;

                foreach (var checksum in siteRoot.Checksums)
                {
                    _RequestChecksumMap.Add(NormaliseRequestPath(checksum.FileName), checksum);
                }
            }
Example #12
0
        public void FileSystemConfiguration_RemoveSiteRoot_Ignores_Sites_Not_Added()
        {
            _FileSystemProvider.AddFolder(@"c:\web");
            var siteRoot = new SiteRoot()
            {
                Folder = @"c:\web"
            };

            _Configuration.RemoveSiteRoot(siteRoot);
            Assert.IsFalse(_Configuration.IsSiteRootActive(siteRoot, false));
        }
Example #13
0
            /// <summary>
            /// Creates a new object.
            /// </summary>
            /// <param name="folder"></param>
            /// <param name="siteRoot"></param>
            public Root(string folder, SiteRoot siteRoot)
            {
                SiteRoot = siteRoot;
                Folder = folder;
                Priority = siteRoot.Priority;

                RequestChecksumMap = new Dictionary<string,ChecksumFileEntry>();
                foreach(var checksum in siteRoot.Checksums) {
                    RequestChecksumMap.Add(NormaliseRequestPath(checksum.FileName), checksum);
                }
            }
Example #14
0
        public void FileSystemConfiguration_IsSiteRootActive_Returns_True_If_SiteRoot_Added()
        {
            _FileSystemProvider.AddFolder(@"c:\web");
            var siteRoot = new SiteRoot()
            {
                Folder = @"c:\web"
            };

            _Configuration.AddSiteRoot(siteRoot);

            Assert.IsTrue(_Configuration.IsSiteRootActive(siteRoot, false));
        }
Example #15
0
        /// <summary>
        /// See interface docs for <see cref="IWebSite"/>.
        /// </summary>
        /// <param name="siteRoot"></param>
        /// <param name="folderMustMatch"></param>
        /// <returns></returns>
        public bool IsSiteRootActive(SiteRoot siteRoot, bool folderMustMatch)
        {
            var result = siteRoot != null;
            if(result) {
                var normalisedSiteRootFolder = NormalisePath(siteRoot.Folder);
                result = _Roots.SingleOrDefault(r => 
                    r.SiteRoot == siteRoot && (!folderMustMatch || (r.Folder.Equals(normalisedSiteRootFolder, StringComparison.OrdinalIgnoreCase)))
                ) != null;
            }

            return result;
        }
Example #16
0
		private void Page_Load(object sender, EventArgs e)
		{
			if (SiteUtils.SslIsAvailable())
				SiteUtils.ForceSsl();
			SecurityHelper.DisableBrowserCache();

			if (Request.IsAuthenticated)
			{
				string returnUrlParam = Page.Request.Params.Get("returnurl");

				if (!String.IsNullOrEmpty(returnUrlParam) && !returnUrlParam.ToLower().Contains("/accessdenied.aspx"))
				{
					returnUrlParam = SecurityHelper.RemoveMarkup(Page.Server.UrlDecode(returnUrlParam));


					string redirectUrl = Page.ResolveUrl(returnUrlParam);
					if (
						((redirectUrl.StartsWith("/")) && (!(redirectUrl.StartsWith("//"))))
						|| (redirectUrl.StartsWith(SiteRoot))
						|| (redirectUrl.StartsWith(SiteRoot.Replace("https://", "http://"))))
					{
						WebUtils.SetupRedirect(this, returnUrlParam);
						return;
					}
				}

				// user is logged in
				WebUtils.SetupRedirect(this, SiteRoot + "/Default.aspx");
				return;
			}

			PopulateLabels();

			login1.SetFocus = true;

			if (siteSettings.LoginInfoTop.Length > 0)
			{
				pnlTopContent.Visible = true;
				litTopContent.Text = siteSettings.LoginInfoTop;
			}

			if (siteSettings.LoginInfoBottom.Length > 0)
			{
				pnlBottomContent.Visible = true;
				litBottomContent.Text = siteSettings.LoginInfoBottom;
			}

			SetupReturnUrlCookie();

			if (siteSettings.DisableDbAuth)
			{ pnlStandardLogin.Visible = false; }
		}
        public static async Task <string> GetSimpsonsGifAsync(SiteRoot site)
        {
            var result = await _http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false);

            var content       = JsonConvert.DeserializeObject <SimpsonsData>(result);
            var frames_result = await _http.GetStringAsync($"https://{site}.com/api/frames/{content.Episode.Key}/{content.Frame.Timestamp}/3000/4000").ConfigureAwait(false);

            var frames = JsonConvert.DeserializeObject <List <Frame> >(frames_result);
            var start  = frames[0].Timestamp;
            var end    = frames[frames.Count - 1].Timestamp;

            return($"https://{site}.com/gif/{content.Episode.Key}/{start}/{end}.gif");
        }
Example #18
0
        /// <summary>
        /// See interface docs for <see cref="IWebSite"/>.
        /// </summary>
        /// <param name="siteRoot"></param>
        public void AddSiteRoot(SiteRoot siteRoot)
        {
            if(siteRoot == null) throw new ArgumentNullException("siteRoot");
            if(String.IsNullOrEmpty(siteRoot.Folder)) throw new ArgumentException("siteRoot.Folder");
            if(!Directory.Exists(siteRoot.Folder)) throw new InvalidOperationException($"{siteRoot.Folder} does not exist");
            if(!Path.IsPathRooted(siteRoot.Folder)) throw new InvalidOperationException($"{siteRoot.Folder} is a relative path - only absolute paths can be site roots");

            var folder = NormalisePath(siteRoot.Folder);
            if(_Roots.Any(r => r.Folder.Equals(folder, StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException($"{siteRoot.Folder} is already a site root");

            _Roots.Add(new Root(folder, siteRoot));
            _Roots.Sort((lhs, rhs) => { return lhs.Priority < rhs.Priority ? -1 : lhs.Priority == rhs.Priority ? 0 : 1; });
        }
Example #19
0
        public void FileSystemConfiguration_RemoveSiteRoot_Removes_Added_Site()
        {
            _FileSystemProvider.AddFolder(@"c:\web");
            var siteRoot = new SiteRoot()
            {
                Folder = @"c:\web"
            };

            _Configuration.AddSiteRoot(siteRoot);
            _Configuration.RemoveSiteRoot(siteRoot);

            Assert.IsFalse(_Configuration.IsSiteRootActive(siteRoot, false));
            Assert.AreEqual(0, _Configuration.GetSiteRootFolders().Count);
        }
Example #20
0
 /// <summary>
 /// Registers or deregisters a single site root with the web site. Call within a lock.
 /// </summary>
 /// <param name="siteRoot"></param>
 private void EnableDisableSiteRoot(SiteRoot siteRoot)
 {
     if (_WebSite != null)
     {
         if (_Enabled)
         {
             _WebSite.AddSiteRoot(siteRoot);
         }
         else
         {
             _WebSite.RemoveSiteRoot(siteRoot);
         }
     }
 }
Example #21
0
        private async Task <SiteRoot> FindOrCreateSite(string authority)
        {
            var result = await _siteRootRepository.GetSingle(sr => sr.Authority == authority);

            if (result == null)
            {
                result = new SiteRoot {
                    Authority = authority
                };
                await _siteRootRepository.Add(result);
            }

            return(result);
        }
        public static DiscordEmbedBuilder EmbedSimpsonsEpisode(SimpsonsData data, SiteRoot site)
        {
            var output = new DiscordEmbedBuilder()
                         .WithTitle(data.Episode.Title)
                         .AddField("Season/Episode", data.Episode.Key, true)
                         .AddField("Writer", (!string.IsNullOrWhiteSpace(data.Episode.Writer)) ? data.Episode.Writer : "Unknown", true)
                         .AddField("Director", (!string.IsNullOrWhiteSpace(data.Episode.Director)) ? data.Episode.Director : "Unknown", true)
                         .WithFooter("Original Air Date: " + data.Episode.OriginalAirDate)
                         .WithImageUrl($"https://{site}.com/img/{data.Frame.Episode}/{data.Frame.Timestamp}.jpg")
                         .WithColor(new DiscordColor("#FFBB22"))
                         .WithUrl(data.Episode.WikiLink);

            return(output);
        }
Example #23
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="pluginStartupParameters"></param>
        public void Initialise(PluginStartupParameters pluginStartupParameters)
        {
            _WebSite = pluginStartupParameters.WebSite;

            if (!String.IsNullOrEmpty(WebRootSubFolder))
            {
                _SiteRoot = new SiteRoot()
                {
                    Folder   = Path.Combine(pluginStartupParameters.PluginFolder, WebRootSubFolder),
                    Priority = Priority,
                };
            }

            if (!String.IsNullOrEmpty(InjectContent))
            {
                var injectContent = InjectContent;
                Func <string, HtmlContentInjector> createInjector = (string pathAndFile) => new HtmlContentInjector()
                {
                    Content     = () => injectContent,
                    Element     = "HEAD",
                    PathAndFile = pathAndFile,
                    Priority    = Priority,
                };
                if (InjectPages.Count == 0)
                {
                    _ContentInjectors.Add(createInjector(null));
                }
                else
                {
                    foreach (var injectPage in InjectPages)
                    {
                        _ContentInjectors.Add(createInjector(injectPage));
                    }
                }
            }

            if (PageHandlers.Count > 0)
            {
                _WebServer = Factory.Singleton.Resolve <IAutoConfigWebServer>().Singleton.WebServer;
                _WebServer.BeforeRequestReceived += WebServer_BeforeRequestReceived;

                foreach (var pageHandler in PageHandlers)
                {
                    _PageHandlers.Add(pageHandler.Key, pageHandler.Value);
                }
            }

            EnableDisableContent();
        }
Example #24
0
        /// <summary>
        /// Creates a new object.
        /// </summary>
        public FileSystemPage(WebSite webSite) : base(webSite)
        {
            var runtime = Factory.Singleton.Resolve<IRuntimeEnvironment>().Singleton;
            var defaultSiteRoot = new SiteRoot() {
                Folder = String.Format("{0}{1}", Path.Combine(runtime.ExecutablePath, "Web"), Path.DirectorySeparatorChar),
                Priority = 0,
            };

            var checksumsFileName = Path.Combine(runtime.ExecutablePath, "Checksums.txt");
            if(!File.Exists(checksumsFileName)) {
                throw new FileNotFoundException($"Cannot find {checksumsFileName}");
            }
            defaultSiteRoot.Checksums.AddRange(ChecksumFile.Load(File.ReadAllText(checksumsFileName), enforceContentChecksum: true));

            AddSiteRoot(defaultSiteRoot);
        }
Example #25
0
        public void FileSystemConfiguration_IsSiteRootActive_Returns_True_If_SiteRoot_Folder_Changed_And_Folders_Are_Significant()
        {
            _FileSystemProvider.AddFolder(@"c:\web");
            _FileSystemProvider.AddFolder(@"c:\other");

            var siteRoot = new SiteRoot()
            {
                Folder = @"c:\web"
            };

            _Configuration.AddSiteRoot(siteRoot);

            siteRoot.Folder = @"c:\other";

            Assert.IsFalse(_Configuration.IsSiteRootActive(siteRoot, true));
        }
Example #26
0
        public void FileSystemConfiguration_IsSiteRootActive_Returns_True_If_Changed_Folder_Points_To_Original_Folder()
        {
            _FileSystemProvider.AddFolder(@"c:\web");
            _FileSystemProvider.AddFolder(@"c:\web\subfolder");

            var siteRoot = new SiteRoot()
            {
                Folder = @"c:\web"
            };

            _Configuration.AddSiteRoot(siteRoot);

            siteRoot.Folder = @"c:\web\subfolder\..";

            Assert.IsTrue(_Configuration.IsSiteRootActive(siteRoot, true));
        }
Example #27
0
        public static async Task <string> GetSimpsonsGifAsync(SiteRoot site)
        {
            var result = await Http.GetStringAsync(string.Format(Resources.URL_Simpsons_Random, site))
                         .ConfigureAwait(false);

            var content      = JsonConvert.DeserializeObject <SimpsonsData>(result);
            var framesResult = await Http
                               .GetStringAsync(string.Format(Resources.URL_Simpsons_Frames, site, content?.Episode.Key,
                                                             content.Frame.Timestamp))
                               .ConfigureAwait(false);

            var frames = JsonConvert.DeserializeObject <List <Frame> >(framesResult);
            var start  = frames?.FirstOrDefault()?.Timestamp;
            var end    = frames?.LastOrDefault()?.Timestamp;

            return(string.Format(Resources.URL_Simpsons_Result, site, content.Episode.Key, start, end));
        }
Example #28
0
        private static DiscordEmbedBuilder EmbedSimpsonsEpisode(SimpsonsData data, SiteRoot site)
        {
            var output = new DiscordEmbedBuilder()
                         .WithTitle(data.Episode.Title)
                         .AddField("Original Air Date", data.Episode.OriginalAirDate, true)
                         .AddField("Writer", !string.IsNullOrWhiteSpace(data.Episode.Writer) ? data.Episode.Writer : "Unknown",
                                   true)
                         .AddField("Director",
                                   !string.IsNullOrWhiteSpace(data.Episode.Director) ? data.Episode.Director : "Unknown", true)
                         .WithImageUrl(string.Format(Resources.URL_Simpsons_Image, site, data.Frame.Episode,
                                                     data.Frame.Timestamp))
                         .WithFooter(data.Episode.Key)
                         .WithColor(new DiscordColor("#FFBB22"))
                         .WithUrl(data.Episode.WikiLink);

            return(output);
        }
Example #29
0
        public void WebSite_AttachSiteToServer_Allows_Default_File_System_Site_Pages_To_Be_Served()
        {
            SiteRoot siteRoot = null;

            _FileSystemServerConfiguration.Setup(r => r.AddSiteRoot(It.IsAny <SiteRoot>())).Callback((SiteRoot s) => {
                siteRoot = s;
            });

            _WebSite.AttachSiteToServer(_WebServer.Object);

            var runtime        = Factory.ResolveSingleton <IRuntimeEnvironment>();
            var expectedFolder = String.Format("{0}{1}", Path.Combine(runtime.ExecutablePath, "Web"), Path.DirectorySeparatorChar);

            Assert.IsNotNull(siteRoot);
            Assert.AreEqual(0, siteRoot.Priority);
            Assert.AreEqual(expectedFolder, siteRoot.Folder);
            Assert.IsTrue(siteRoot.Checksums.Count > 0);
        }
Example #30
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            TextMode = TextBoxMode.MultiLine;
            Rows     = 10;
            Columns  = 70;

            htmlEncode = WebConfigSettings.CKeditorEncodeBrackets;

            if (SiteRoot.StartsWith("~/"))
            {
                SiteRoot = ResolveUrl(SiteRoot);
            }

            if (DisableViewState)
            {
                EnableViewState = false;
            }
        }