/// <summary> /// Constructor /// </summary> public MainForm() { InitializeComponent(); //read in the site info from the settings xml file _webSites = new WebSites(); _webSites.Read(out _startAutomatically, out _hideAtStartup, out _allowRemoteConnections); // Create a listener for ServerManager messages _managerListener = new ServerManagerListener(Program.SERVER_MANAGER_BASE_PORT, this, _webSites); _managerListener.StartListening(); // Create the help site and start the server unless another instance of the app has already done it _helpSite = Program.CreateHelpWebSite(); if (!Program.PortIsInUse(_helpSite.Port, false) && (_helpSite.PhysicalPath != String.Empty)) { _helpSite.WebServer = new Server(_helpSite.Port, _helpSite.VirtualPath, _helpSite.PhysicalPath, _helpSite.DefaultPage, false, false); } //Populate the list box and update the link label UpdateUI(); //If we are set to start the servers automatically, do it now if (_startAutomatically) { toolStripStatusLabel.Text = StartOrStopAll(true); } else { //otherwise just update the tray icon text notifyIcon.Text = Program.ApplicationTitleAndVersion; notifyIcon.Text += "\r\nStopped"; } }
public IRobot CreateRobot(WebSite webSite, UnityContainer container) { if (webSite == WebSite.Amazon) return container.Resolve<AmazonRobot>(); if (webSite == WebSite.ZhaoCaiBao) return container.Resolve<ZhaoCaiBaoRobot>(); return null; }
public Post(WebSite source, string headline, Bitmap bmp) { this.headline = headline; this.bmp = bmp; this.description = String.Empty; this.date = DateTime.MinValue; this.url = String.Empty; this.source = source; }
public Post(WebSite source, string headline, Bitmap bmp, string url, string description) { this.headline = headline; this.bmp = bmp; this.description = description; this.url = url; this.date = DateTime.MinValue; this.source = source; }
public void SetWebSiteLoggingSettings(WebSite webSite) { using (var srvman = GetServerManager()) { var iisObject = srvman.Sites[webSite.SiteId]; // Website logging is enabled by default iisObject.LogFile.Enabled = true; // Set website logs folder if (!String.IsNullOrEmpty(webSite.LogsPath)) iisObject.LogFile.Directory = webSite.LogsPath; // srvman.CommitChanges(); } }
public void TableTestShortInfo() { WebSite.Init(typeof(W3CSite)); W3CSite.TablePage.IsOpened(); var headers = W3CSite.TablePage.CompaniesShort.Columns.AllHeaders; CheckHeaders(headers); var companies = W3CSite.TablePage.CompaniesShort.Entities(); Assert.AreEqual(companies.Select(c => c.ToString()).Print(";"), "Alfreds Futterkiste, Germany;" + "Centro comercial Moctezuma, Mexico;" + "Ernst Handel, Austria;" + "Island Trading, UK;" + "Laughing Bacchus Winecellars, Canada;" + "Magazzini Alimentari Riuniti, Italy" ); }
public void TableTest() { WebSite.Init(typeof(W3CSite)); W3CSite.TablePage.IsOpened(); var headers = W3CSite.TablePage.Companies.Columns.AllHeaders; CheckHeaders(headers); var companies = W3CSite.TablePage.Companies.Entities(); Assert.AreEqual(companies.Select(c => c.ToString()).Print(";"), "Alfreds Futterkiste, Maria Anders, Germany;" + "Centro comercial Moctezuma, Francisco Chang, Mexico;" + "Ernst Handel, Roland Mendel, Austria;" + "Island Trading, Helen Bennett, UK;" + "Laughing Bacchus Winecellars, Yoshi Tannamuri, Canada;" + "Magazzini Alimentari Riuniti, Giovanni Rovelli, Italy" ); }
public GetPagesContent( WebSite webSite, string tag, int pages, Action <int> action, TimeSpan timeOut, int maxSize, int poolCount) : base(webSite, timeOut, maxSize, poolCount) { m_pages = pages; m_action = action; m_tag = tag.Trim(); }
private string GetBaseUrl(WebSite site, string domain) { //string baseurl = website.BaseUrl(); var hostname = string.Format("{0}.{1}", site.Name, domain); var baseurl = string.Empty; if (site.ForceSSL) { var uri = new UriBuilder("https", hostname, 443); baseurl = uri.Uri.AbsoluteUri; } else { var uri = new UriBuilder("http", hostname, 80); baseurl = uri.Uri.AbsoluteUri; } return(baseurl); }
public void WhenIHaveNoCurrentModelledApprenticeships() { EstimateFundsStartPage page = new EstimateFundsStartPage(WebSite.getDriver()); page.ClickStartForAccountWithoutApprenticeships(); EstimateCostsPage estimateCostsPage = new EstimateCostsPage(WebSite.getDriver()); if (!WebSite.CurrentUrl.Contains("apprenticeship/add")) { var isAnyapprenticeshipExist = estimateCostsPage.IsApprenticeshipsTableVisible(); while (isAnyapprenticeshipExist) { estimateCostsPage.RemoveFirstApprenticeship(); isAnyapprenticeshipExist = estimateCostsPage.IsApprenticeshipsTableVisible(); } } }
private static WebSite BuildTestSite(long siteId, string name) { var s = new WebSite { SiteId = siteId, DomainName = name + ".dev.bigblackspider.com", Description = $"Unit test website for '{name}'.", MailDomainName = name + ".mail.bigblackspider.com" }; s.Details.Add("$SHORT-DESCRIPTION$", "Test web site."); s.Details.Add("$MAIN-HEADING$", $"{name} Unit Test Web Site"); s.Details.Add("$MAIN-TEXT$", $"This is a unit test website for '<b>{name}</b>,'."); s.Details.Add("$ABOUT-HEADING$", $"All About {name}'"); s.Details.Add("$ABOUT-TEXT$", $"Some text that describes the about section for domain '<b><i>{s.DomainName}</i></b>'."); return(s); }
public static HashSet <string> GetCultureFromContentRepo(WebSite website) { HashSet <string> cultures = new HashSet <string>(); var allcontents = website.SiteDb().TextContent.All(); foreach (var item in allcontents) { foreach (var langcontent in item.Contents) { if (langcontent != null && langcontent.Lang != null) { cultures.Add(langcontent.Lang); } } } return(cultures); }
public k GetBySiteId(object SiteId) { Guid id = Kooboo.Lib.Helper.IDHelper.ParseKey(SiteId); WebSite find = _findsite(id); if (find == null) { return(null); } RenderContext newcontext = new RenderContext(); newcontext.Request = this.RenderContext.Request; newcontext.User = this.RenderContext.User; newcontext.WebSite = find; newcontext.IsSiteBinding = true; return(new k(newcontext)); }
public static void SetupApplications(WebSite currentWebSite) { ApplicationSetUp.SetSourceRootPath(RuntimeEnvironment.GetSourceFolder()); var details = new Dictionary <WebSite, WebSiteDetails>(); foreach (WebSite webSite in Enum.GetValues(typeof(WebSite))) { var host = Instance.GetProperty(GetWebSitePrefix(webSite) + ".host", true); var port = Instance.GetIntProperty(GetWebSitePrefix(webSite) + ".port", -1); var applicationPath = Instance.GetProperty(GetWebSitePrefix(webSite) + ".applicationpath", true); details.Add(webSite, new WebSiteDetails(host, port, applicationPath)); } ApplicationSetUp.SetWebSites(details); ApplicationSetUp.SetCurrentApplication(currentWebSite); }
IList <TinyUrlMapping> IApplicationsRepository.GetMappings(WebSite webSite, Guid?verticalId, bool secure, string longUrl, Guid contextId, string mimeType, int instance) { using (var dc = new ApplicationsDataContext(_connectionFactory.CreateConnection()).AsReadOnly()) { var criteria = new MappingCriteria { WebSite = webSite, VerticalId = verticalId, Secure = secure, LongUrl = longUrl, ContextId = contextId, MimeType = mimeType, Instance = instance, }; return(GetMappingsByCriteria(dc, criteria, _webSiteQuery).ToList()); } }
public new String LEInstallCertificate(WebSite website, string email) { Log.WriteStart("LEInstallCertificate IIS100"); Runspace runSpace = null; //SSLCertificate cert = null; object result = null; object[] errors = null; try { Log.WriteInfo("Website: {0}", website.SiteId); // Get the WebsiteID string siteid = GetSiteID(website.SiteId); Log.WriteInfo("Found Website ID: SiteName {1} ID: {0}", siteid, website.SiteId); // This sets the correct path for the Exe file. var Path = AppDomain.CurrentDomain.BaseDirectory; Log.WriteInfo("SolidCP Server path: {0}", Path); string command = AppDomain.CurrentDomain.BaseDirectory + "bin\\LetsEncrypt\\wacs.exe"; runSpace = OpenRunspace(); var scripts = new List <string> { string.Format("& '{0}' --target iissite --installation iis --siteid {2} --emailaddress {1} --accepttos --usedefaulttaskuser", command, email, siteid) }; Log.WriteInfo("LE Command Strïng: {0}", scripts); result = ExecuteLocalScript(runSpace, scripts, out errors); Log.WriteInfo(result.ToString()); CloseRunspace(runSpace); } catch (Exception ex) { Log.WriteError("Error adding Lets Encrypt certificate IIS100", ex); return(ex.ToString()); throw; } Log.WriteEnd("LEInstallCertificate IIS100"); return(result.ToString()); }
private void WebSiteListSave() { try { if (_webSiteList == null) { ShowErrorMessage("Список сайтов пуст!"); return; } //Если имя файла не указано if (_dataFileName == "" || _dataFileName == null) { ShowErrorMessage("Путь к файлу не указан"); return; } //Если файл не существует if (!File.Exists(_dataFileName)) { using (File.Create(Directory.GetCurrentDirectory() + "\\" + _dataFileName)); } using (StreamWriter sw = new StreamWriter(_dataFileName, false)) { for (int i = 0; i < _webSiteList.Count; i++) { try { WebSite webSite = _webSiteList[i]; sw.WriteLine(webSite.Name + '#' + webSite.URL + '#' + webSite.AvialabilityCheckInterval); } catch (Exception ex) { ShowErrorMessage("" + ex); } } } } catch (Exception ex) { ShowErrorMessage("" + ex); } }
public void XPathPOC(string RefURL, string XPathForm, string Parameter) { this.mainfrm.NavigatePage(RefURL, RequestType.GET, ""); string[] paraNameValue = WebSite.GetParaNameValue(Parameter, '='); string str = paraNameValue[0]; string expression = paraNameValue[1]; string[] strArray2 = new string[2]; if (XPathForm.IndexOf('^') > 0) { strArray2 = WebSite.GetParaNameValue(XPathForm, '^'); } else { if (XPathForm.IndexOf('?') <= 0) { return; } strArray2 = WebSite.GetParaNameValue(XPathForm, '?'); } string[] strArray3 = strArray2[1].Split(new char[] { '&' }); MessageBox.Show("* It Will Open The XPath Page And Fill In Input Fields Automatically! \r\n* When Page Load Completed, Click OK To Continue!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); this.mainfrm.DisplayProgress("Preparing XPath Data..."); foreach (HtmlElement element in this.WCRBrowser.Document.All) { for (int i = 0; i < strArray3.Length; i++) { string[] strArray4 = WebSite.GetParaNameValue(strArray3[i], '='); if (element.Name.Equals(strArray4[0])) { element.SetAttribute("value", GlobalObject.unescape(WebSite.RemoveTestInput(strArray4[1]))); } } if (element.Name.Equals(str)) { element.SetAttribute("value", GlobalObject.unescape(WebSite.RemoveTestInput(expression) + "%27] | * | user[@role=%27admin")); } } this.mainfrm.DisplayProgress("Done"); MessageBox.Show("* XPath Data Filled OK, You Can View Or Change It Now!\r\n* Then Click Button To Submit The Form Manually! \r\n* You Will Get The Response Possibly Include Confidential Data!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
public static void Setup() { Timer _timer = new Timer(); WebSettings.InitNUnitDefault(); WinProcUtils.KillAllRunWebDrivers(); if (!JDISettings.DriverFactory.HasDrivers()) { WebSettings.UseDriver(DriverTypes.Chrome); } _timer = new Timer(); WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); WebDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(5)); WebDriver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5)); WebSite.Init(typeof(EbaySite)); }
public static string TextContentAddScript(WebSite Site, string folderName) { var fields = GetTextContentFields(Site, folderName); if (fields != null && fields.Any()) { string js = "var obj={}; \r\n"; foreach (var item in fields) { js += "obj." + item + "=k.request." + item + ";\r\n"; } js += "obj.folder='" + folderName + "'\r\n"; js += "k.site.textContents.add(obj); \r\n"; // js += "k.response.write('ok');"; return(js); } return(null); }
public async Task <IActionResult> Put(int webSiteId, [FromBody] WebSiteModel value) { if (!ModelState.IsValid) { return(ValidationProblem(ModelState)); } WebSite webSite = _webSiteMapper.ModelToEntity(value); webSite.Id = webSiteId; bool success = await _webSiteService.UpdateWebSite(webSite); if (!success) { return(NotFound()); } return(Ok()); }
public static ClusterSiteEditModel GetModel(WebSite site, string destPrimaryDomain) { ClusterSiteEditModel editmodel = new ClusterSiteEditModel(); editmodel.PrimaryDomain = destPrimaryDomain; editmodel.Name = site.Name; editmodel.OrganizationId = site.OrganizationId; var bindings = Kooboo.Data.GlobalDb.Bindings.GetByWebSite(site.Id); foreach (var item in bindings) { editmodel.Domains.Add(item.FullName); } editmodel.Settiing = ImportExport.GetSiteSetting(site); return(editmodel); }
public void Test() { using (var session = Domain.OpenSession()) { using (var t = session.OpenTransaction()) { var webSite = new WebSite(); webSite.Title = "Title"; t.Complete(); } using (var t = session.OpenTransaction()) { var webSite = session.Query.All <WebSite>().First(); var result = session.Query.All <ContentReference>() .Where( r => r.ReferenceType == ContentReferenceType.Embedded && r.ContentID.In(session.Query.All <NewsList>().Where(nl => nl.WebSite == webSite).Select(nl => nl.Id))); var list = result.ToList(); t.Complete(); } } }
public static string FullStartUrl(this WebSite site) { var binding = Data.GlobalDb.Bindings.GetByWebSite(site.Id).FirstOrDefault(); string starturl = string.Empty; if (binding != null) { starturl = "http://" + binding.FullName; if (AppSettings.CurrentUsedPort != 80 && AppSettings.CurrentUsedPort > 0) { starturl = starturl + ":" + AppSettings.CurrentUsedPort; } starturl = starturl + "/"; starturl = Lib.Helper.UrlHelper.Combine(starturl, site.StartRoutePath()); } return(starturl); }
public async static Task <WebSite> CheckUrlType(string url) { WebSite webSite = WebSite.None; bool enablecookie = false; string label = ""; (bool result, string title) = await Net.TestAndGetTitle(url, enablecookie, "", label); if (result) { //其他,进行判断 if (title.ToLower().IndexOf("javbus") >= 0 && title.IndexOf("歐美") < 0) { webSite = WebSite.Bus; } else if (title.ToLower().IndexOf("javbus") >= 0 && title.IndexOf("歐美") >= 0) { webSite = WebSite.BusEu; } else if (title.ToLower().IndexOf("javlibrary") >= 0) { webSite = WebSite.Library; } else if (title.ToLower().IndexOf("fanza") >= 0) { webSite = WebSite.DMM; } else if (title.ToLower().IndexOf("jav321") >= 0) { webSite = WebSite.Jav321; } else if (title.ToLower().IndexOf("javdb") >= 0) { webSite = WebSite.DB; } else { webSite = WebSite.None; } } return(webSite); }
private void SaveWebSite() { if (!Page.IsValid) { return; } // load original web site item WebSite site = ES.Services.WebServers.GetWebSite(PanelRequest.ItemID); // collect form data site.FrontPageAccount = frontPageUsername.Text; site.ColdFusionInstalled = chkCfExt.Checked; site.CreateCFVirtualDirectories = chkVirtDir.Checked; // other controls webSitesExtensionsControl.SaveWebItem(site); webSitesHomeFolderControl.SaveWebItem(site); webSitesMimeTypesControl.SaveWebItem(site); webSitesCustomHeadersControl.SaveWebItem(site); webSitesCustomErrorsControl.SaveWebItem(site); webSitesHeliconZooControl.SaveWebItem(site); // update web site try { int result = ES.Services.WebServers.UpdateWebSite(site); if (result < 0) { ShowResultMessage(result); return; } ShowSuccessMessage("WEB_UPDATE_SITE"); } catch (Exception ex) { ShowErrorMessage("WEB_UPDATE_SITE", ex); return; } }
public async Task Logical_Deletion_ById() { try { Guid?id = null; using (var ctx = new TestDbContext()) { var entity = new WebSite { Url = "http://dotnet.microsoft.com/" }; ctx.Add(entity); await ctx.SaveChangesAsync().ConfigureAwait(false); id = entity.Id; } using (var ctx = new TestDbContext()) { var webSites = ctx.Set <WebSite>().ToList(); webSites.Count().Should().Be(1); webSites.Count(w => w.Deleted).Should().Be(0); } using (var adapater = GetRepository()) { var entity = new TestDbContext().Set <WebSite>().FirstOrDefault(); entity.Should().NotBeNull(); adapater.MarkIdForDelete <WebSite>(id); await adapater.SaveAsync().ConfigureAwait(false); } using (var ctx = new TestDbContext()) { var webSites = ctx.Set <WebSite>().ToList(); webSites.Count().Should().Be(1); webSites.Count(w => w.Deleted).Should().Be(1); webSites[0].DeletionDate.Should().BeSameDateAs(DateTime.Today); } } finally { DeleteAll(); } }
public static string GetCustomErrorUrl(WebSite website, int statusCode) { if (website.CustomErrors.ContainsKey(statusCode)) { var page = website.CustomErrors[statusCode]; Guid PageId = default(Guid); if (System.Guid.TryParse(page, out PageId)) { return(ObjectService.GetObjectRelativeUrl(website.SiteDb(), PageId, ConstObjectType.Page)); } else { return(page); } } else { if (statusCode == 404) { return(DataConstants.Default404Page); } else if (statusCode == 500) { return(DataConstants.Default500Page); } else if (statusCode == 403) { return(DataConstants.Default403Page); } else if (statusCode == 407) { return(DataConstants.Default407Page); } else if (statusCode == 402) { return(DataConstants.Default402Page); } return(DataConstants.DefaultError); } }
public WebSite Create(ApiCall call) { Sites.DataSources.DataSourceHelper.InitIDataSource(); string fulldomain = call.GetValue("FullDomain"); if (string.IsNullOrEmpty(fulldomain)) { string RootDomain = call.GetValue("RootDomain"); string SubDomain = call.GetValue("SubDomain"); fulldomain = SubDomain + "." + RootDomain; } string sitename = call.GetValue("SiteName"); if (string.IsNullOrEmpty(sitename) || string.IsNullOrEmpty(fulldomain)) { return null; } WebSite newsite = Kooboo.Sites.Service.WebSiteService.AddNewSite(call.Context.User.CurrentOrgId, sitename, fulldomain, call.Context.User.Id); return newsite; }
public async Task Update_NotExisting_InBDD_AsExpected() { try { using (var repo = new RepositoryBase(new MongoDataReaderAdapter(), new MongoDataWriterAdapter())) { var b = new WebSite { Url = "http://www.microsoft.com" }; b.FakePersistenceId(Guid.NewGuid()); repo.MarkForUpdate(b); await Assert.ThrowsAsync <InvalidOperationException>(repo.SaveAsync); } } finally { DeleteAll(); } }
public async Task DeleteAsync_ShouldInvokeDeleteAsync() { // Arrange var existingWebSite = new WebSite(); this.webSiteMockRepository.Setup(e => e.GetByIdAsync(It.IsAny <int>())) .Returns(Task.FromResult(existingWebSite)); this.webSiteMockRepository.Setup(e => e.SoftDeleteAsync(existingWebSite)) .Returns(Task.FromResult(existingWebSite.IsDeleted = true)); // Act await webSiteService.DeleteAsync(It.IsAny <int>()); // Assert this.webSiteMockRepository.Verify( x => x.SoftDeleteAsync( It.Is <WebSite>( y => y.IsDeleted == true)), Times.Once()); }
public WebSiteData GetInfo() { InternetInformationServer iis = new InternetInformationServer(); WebSite webSite = iis.GetWebSite(_siteName); if (webSite == null) { return(null); } var siteData = new WebSiteData(); var dirSettings = webSite.DirectorySettings; siteData.AppPoolName = (string)dirSettings.GetInstance(dirSettings.Path).GetPropertyValue("AppPoolId"); siteData.PhysicalPath = (string)dirSettings.GetInstance(dirSettings.Path).GetPropertyValue("Path"); siteData.SiteStarted = webSite.CurrentState == ServerState.Started; siteData.AppPoolStarted = true; return(siteData); }
public async Task Update_NotExisting_InBDD_Should_Throw_EFException() { try { using (var adapater = GetRepository()) { var b = new WebSite { Url = "http://www.microsoft.com" }; b.FakePersistenceId(Guid.NewGuid()); adapater.MarkForUpdate(b); await Assert.ThrowsAsync <DbUpdateConcurrencyException>(adapater.SaveAsync); } } finally { DeleteAll(); } }
public static Uri GetKuduServiceUri(WebSite site, string path) { string repositoryUri = (from p in site.SiteProperties.Properties where p.Name == Constants.RepositoryUri select p.Value).First(); string userName = (from p in site.SiteProperties.Properties where p.Name == Constants.PublishingUsername select p.Value).First(); string password = (from p in site.SiteProperties.Properties where p.Name == Constants.PublishingPassword select p.Value).First(); UriBuilder uri = new UriBuilder(repositoryUri); uri.UserName = userName; uri.Password = password; uri.Path = path; return uri.Uri; }
public void Create_new_web_site_with_many_bindings() { var newsite = default(WebSiteRow); var newbindings = default(IList <BindingRow>); try { var site = CreateWebSiteWithBindings(10); var id = site.Id.ToString(); newsite = _webSiteTable.Query.Where(t => t.RowKey == id).FirstOrDefault(); Assert.IsNotNull(newsite); Assert.AreEqual(site.Name, newsite.Name); Assert.AreEqual(site.Description, newsite.Description); newbindings = _bindingTable.Query.Where(b => b.WebSiteId == site.Id).ToList(); Assert.IsNotNull(newbindings); Assert.AreEqual(10, newbindings.Count()); WebSite siteb = _repository.RetrieveWebSiteWithBindings(site.Id); Assert.IsNotNull(siteb); Assert.IsNotNull(siteb.Bindings); Assert.AreEqual(10, siteb.Bindings.Count()); } finally { if (newsite != null) { _webSiteTable.Delete(newsite); } if (newbindings != null && newbindings.Any()) { _bindingTable.Delete(newbindings); } } }
private void WebSiteCheck(WebSite webSite) { do { try { var request = (HttpWebRequest)WebRequest.Create(webSite.URL); request.Timeout = Convert.ToInt16(webSite.AvialabilityCheckInterval) - 1; request.AllowAutoRedirect = false; request.Method = "HEAD"; _isAvialability = false; var StopWatch = Stopwatch.StartNew(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { _isAvialability = true; webSite.SetStatus("Available"); webSite.SetPing(Convert.ToString(StopWatch.ElapsedMilliseconds)); } else { _isAvialability = true; webSite.SetStatus("Founded"); webSite.SetPing(" --- "); } } StopWatch.Stop(); request = null; StopWatch = null; } catch (WebException wex) { _isAvialability = false; webSite.SetStatus("Not Available"); webSite.SetPing(" --- "); //ShowErrorMessage("" + wex); } Thread.Sleep(Convert.ToInt16(webSite.AvialabilityCheckInterval)); } while (_enable); }
public new SSLCertificate GetCurrentSiteCertificate(WebSite website) { using (var srvman = GetServerManager()) { var site = srvman.Sites[website.SiteId]; var sslBinding = site.Bindings.First(b => b.Protocol == "https"); // If the certificate is in the central store if (((SslFlags)Enum.Parse(typeof(SslFlags), sslBinding["sslFlags"].ToString())).HasFlag(SslFlags.CentralCertStore)) { // Let's try to match binding host and certificate filename var path = GetCCSPath(sslBinding.Host); if (File.Exists(path)) { var fileStream = File.OpenRead(path); // Read certificate data from file var certData = new byte[fileStream.Length]; fileStream.Read(certData, 0, (int) fileStream.Length); var cert = new X509Certificate2(certData, CCSCommonPassword); fileStream.Close(); return GetSSLCertificateFromX509Certificate2(cert); } } else { var currentHash = Convert.ToBase64String(sslBinding.CertificateHash); return GetServerCertificates().FirstOrDefault(c => Convert.ToBase64String(c.Hash) == currentHash); } } return null; }
public void AddBinding(X509Certificate2 certificate, WebSite website) { using (var srvman = GetServerManager()) { // Look for dedicated ip var dedicatedIp = SiteHasBindingWithDedicatedIp(srvman, website); // Look for all the hostnames this certificate is valid for if we are using SNI var hostNames = new List<string>(); if (!dedicatedIp) { hostNames.AddRange(certificate.Extensions.Cast<X509Extension>() .Where(e => e.Oid.Value == "2.5.29.17") // Subject Alternative Names .SelectMany(e => e.Format(true).Split(new[] {"\r\n", "\n", "\n"}, StringSplitOptions.RemoveEmptyEntries).Where(s => s.Contains("=")).Select(s => s.Split('=')[1])).Where(s => !s.Contains(" "))); } var simpleName = certificate.GetNameInfo(X509NameType.SimpleName, false); if (hostNames.All(h => h != simpleName)) { hostNames.Add(simpleName); } var wildcardHostName = hostNames.SingleOrDefault(h => h.StartsWith("*.")); // If a wildcard certificate is used if (wildcardHostName != null) { if (!dedicatedIp) { // If using a wildcard ssl and not a dedicated IP, we take all the matching bindings on the site and use it to bind to SSL also. hostNames.Remove(wildcardHostName); hostNames.AddRange(website.Bindings.Where(b => !string.IsNullOrEmpty(b.Host) && b.Host.EndsWith(wildcardHostName.Substring(2))).Select(b => b.Host)); } } // For every hostname foreach (var hostName in hostNames) { var bindingIpAddress = string.IsNullOrEmpty(website.SiteInternalIPAddress) ? website.SiteIPAddress : website.SiteInternalIPAddress; var bindingInformation = string.Format("{0}:443:{1}", bindingIpAddress ?? "*", dedicatedIp ? "" : hostName); Binding siteBinding = UseCCS ? srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, "https") : srvman.Sites[website.SiteId].Bindings.Add(bindingInformation, certificate.GetCertHash(), CertificateStoreName); if (UseSNI && !dedicatedIp) { siteBinding.SslFlags |= SslFlags.Sni; } if (UseCCS) { siteBinding.SslFlags |= SslFlags.CentralCertStore; } } srvman.CommitChanges(); } }
public PostsFoundEventArgs(Post[] posts, WebSite site) { this.posts = posts; this.site = site; }
public WebSite GetWebSiteFromIIS(string siteId) { using (var srvman = GetServerManager()) { var webSite = new WebSite(); // var iisObject = srvman.Sites[siteId]; // webSite.SiteId = webSite.Name = iisObject.Name; // if (iisObject.LogFile.Enabled) { webSite.LogsPath = iisObject.LogFile.Directory; webSite[WebSite.IIS7_LOG_EXT_FILE_FIELDS] = iisObject.LogFile.LogExtFileFlags.ToString(); } // Read instant website id webSite[WebSite.IIS7_SITE_ID] = GetWebSiteIdFromIIS(siteId, "W3SVC{0}"); // Read web site iisAppObject pool name webSite.ApplicationPool = iisObject.Applications["/"].ApplicationPoolName; // return webSite; } }
public new SSLCertificate InstallCertificate(SSLCertificate cert, WebSite website) { try { var response = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; if (response == null) { throw new Exception("Cannot create instance of X509Enrollment.CX509Enrollment"); } response.Initialize(X509CertificateEnrollmentContext.ContextMachine); response.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedRoot, cert.Certificate, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, null ); // At this point, certificate has been installed into "Personal" store // We need to move it into "WebHosting" store // Get certificate var servercert = GetServerCertificates(StoreName.My.ToString()).Single(c => c.FriendlyName == cert.FriendlyName); // Get certificate data - the one we just added to "Personal" store var storeMy = new X509Store(StoreName.My, StoreLocation.LocalMachine); storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts2 = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); var certData = existCerts2[0].Export(X509ContentType.Pfx); storeMy.Close(); var x509Cert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); if (UseCCS) { // Revert to InstallPfx to install new certificate - this also adds binding InstallPfx(certData, string.Empty, website); } else { // Add new certificate to "WebHosting" store var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); store.Close(); } // Remove certificate from "Personal" store storeMy.Open(OpenFlags.MaxAllowed); X509CertificateCollection existCerts = storeMy.Certificates.Find(X509FindType.FindBySerialNumber, servercert.SerialNumber, false); storeMy.Remove((X509Certificate2)existCerts[0]); storeMy.Close(); // Fill object with certificate data cert.SerialNumber = servercert.SerialNumber; cert.ValidFrom = servercert.ValidFrom; cert.ExpiryDate = servercert.ExpiryDate; cert.Hash = servercert.Hash; cert.DistinguishedName = servercert.DistinguishedName; if (!UseCCS) { if (CheckCertificate(website)) { DeleteCertificate(GetCurrentSiteCertificate(website), website); } AddBinding(x509Cert, website); } } catch (Exception ex) { Log.WriteError("Error adding SSL certificate", ex); cert.Success = false; } return cert; }
private static HostNameSslState ToNameSslState(WebSite.WebSiteHostNameSslState state) { return new HostNameSslState { Name = state.Name, SslState = (SslState) (int) state.SslState }; }
public string CreateSite(WebSite site) { // ensure site bindings if (site.Bindings == null || site.Bindings.Length == 0) throw new ApplicationException("SiteServerBindingsEmpty"); // ensure site name if (String.IsNullOrEmpty(site.Name)) throw new ApplicationException("SiteNameEmpty"); // ensure physical site content path if (String.IsNullOrEmpty(site.ContentPath)) throw new ApplicationException("SiteContentPathEmpty"); using (var srvman = GetServerManager()) { // var iisObject = srvman.Sites.Add(site.Name, site.ContentPath, 80); // iisObject.Applications[0].ApplicationPoolName = site.ApplicationPool; // site.SiteId = iisObject.Name; // iisObject.ServerAutoStart = true; // srvman.CommitChanges(); // return iisObject.Name; } }
/// <summary> /// This is the constructor that is used when command line parameters are used /// </summary> /// <param name="PhysicalPath"></param> /// <param name="VirtualPath"></param> /// <param name="Port"></param> /// <param name="DefaultPage"></param> /// <param name="AllowRemoteConnection"></param> /// <param name="LogPageRequests"></param> public SmallUIForm(string PhysicalPath, string VirtualPath, int Port, string DefaultPage, bool AllowRemoteConnection, bool LogPageRequests) { InitializeComponent(); _webSite.PhysicalPath = PhysicalPath; _webSite.VirtualPath = VirtualPath; _webSite.Port = Port; _webSite.DefaultPage = DefaultPage; _webSite.LogPageRequests = LogPageRequests; _allowRemoteConnection = AllowRemoteConnection; txtPhysicalPath.Text = _webSite.PhysicalPath; txtVirtualPath.Text = _webSite.VirtualPath.Substring(1); txtPortNumber.Text = _webSite.Port.ToString(); txtDefaultPage.Text = _webSite.DefaultPage; linkLabel.Text = _webSite.Url; chkAllowRemoteConnection.Checked = _allowRemoteConnection; chkLogPageRequests.Checked = _webSite.LogPageRequests; // Create a listener for ServerManager messages _webSites = new WebSites(); _webSites.Add("FormSite", _webSite); _managerListener = new ServerManagerListener(Program.SERVER_MANAGER_BASE_PORT, this, _webSites); _managerListener.StartListening(); // Create the help site and start the server unless another instance of the app has already done it _helpSite = Program.CreateHelpWebSite(); if (!Program.PortIsInUse(_helpSite.Port, false) && (_helpSite.PhysicalPath != String.Empty)) { _helpSite.WebServer = new Server(_helpSite.Port, _helpSite.VirtualPath, _helpSite.PhysicalPath, _helpSite.DefaultPage, false, false); } // Set the main window title this.Text = String.Format("{0} [{1}]", Program.ApplicationTitle, _webSite.Port.ToString()); }
public override System.Web.Mvc.ActionResult Create(WebSite.Models.Settings siteSettings) { var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.Create); callInfo.RouteValueDictionary.Add("siteSettings", siteSettings); return callInfo; }
public new SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate; try { certificate = GetCurrentSiteCertificate(website); } catch (Exception ex) { certificate = new SSLCertificate { Success = false, Certificate = ex.ToString() }; } return certificate ?? (new SSLCertificate {Success = false, Certificate = "No certificate in binding on server, please remove or edit binding"}); }
//Checks to see if the site has a certificate public bool CheckCertificate(WebSite website) { using (var sm = GetServerManager()) { // Site site = sm.Sites[website.SiteId]; // Just exit from the loop if https binding found foreach (Binding bind in site.Bindings.Where(bind => bind.Protocol == "https")) return true; // return false; } }
/// <summary> /// There are no comments for WebSites in the schema. /// </summary> public void AddToWebSites(WebSite webSite) { base.AddObject("WebSites", webSite); }
public void SetWebSite(WebSite webSite) { WebSite = webSite; }
public new ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { // This method removes all https bindings and all certificates associated with them. // Old implementation (IIS70) removed a single binding (there could not be more than one) and the first certificate that matched via serial number var result = new ResultObject { IsSuccess = true }; if (certificate == null) { return result; } try { var certificatesAndStoreNames = new List<Tuple<string, byte[]>>(); // User servermanager to get aLL SSL-bindings on this website and try to remove the certificates used using (var srvman = GetServerManager()) { var site = srvman.Sites[website.Name]; var bindings = site.Bindings.Where(b => b.Protocol == "https"); foreach (Binding binding in bindings.ToList()) { if (binding.SslFlags.HasFlag(SslFlags.CentralCertStore)) { if (!string.IsNullOrWhiteSpace(CCSUncPath) && Directory.Exists(CCSUncPath)) { // This is where it will be if CCS is used var path = GetCCSPath(certificate.Hostname); if (File.Exists(path)) { File.Delete(path); } // If binding with hostname, also try to delete with the hostname in the binding // This is because if SNI is used, several bindings are created for every valid name in the cerificate, but only one name exists in the SSLCertificate if (!string.IsNullOrEmpty(binding.Host)) { path = GetCCSPath(binding.Host); if (File.Exists(path)) { File.Delete(path); } } } } else { var certificateAndStoreName = new Tuple<string, byte[]>(binding.CertificateStoreName, binding.CertificateHash); if (!string.IsNullOrEmpty(binding.CertificateStoreName) && !certificatesAndStoreNames.Contains(certificateAndStoreName)) { certificatesAndStoreNames.Add(certificateAndStoreName); } } // Remove binding from site site.Bindings.Remove(binding); } srvman.CommitChanges(); foreach (var certificateAndStoreName in certificatesAndStoreNames) { // Delete all certs with the same serialnumber in Store var store = new X509Store(certificateAndStoreName.Item1, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, BitConverter.ToString(certificateAndStoreName.Item2).Replace("-", ""), false); foreach (var cert in certs) { store.Remove(cert); } store.Close(); } } } catch (Exception ex) { Log.WriteError(String.Format("Unable to delete certificate for website {0}", website.Name), ex); result.IsSuccess = false; result.AddError("", ex); } return result; }
private static Certificate ToCertificate(WebSite.WebSiteSslCertificate certificate) { return new Certificate { FriendlyName = certificate.FriendlyName, SubjectName = certificate.SubjectName, HostName = certificate.HostNames.FirstOrDefault(), PfxBlob = certificate.PfxBlob, SiteName = certificate.SiteName, SelfLink = certificate.SelfLinkUri, Issuer = certificate.Issuer, IssueDate = certificate.IssueDate.Value, ExpirationDate = certificate.ExpirationDate.Value, Password = certificate.Password, Thumbprint = certificate.Thumbprint, Valid = certificate.IsValid }; }
public new SSLCertificate InstallPfx(byte[] certificate, string password, WebSite website) { SSLCertificate newcert = null, oldcert = null; // Ensure we perform operations safely and preserve the original state during all manipulations, save the oldcert if one is used if (CheckCertificate(website)) { oldcert = GetCurrentSiteCertificate(website); } X509Certificate2 x509Cert; var store = new X509Store(CertificateStoreName, StoreLocation.LocalMachine); if (UseCCS) { // We need to use this constructor or we won't be able to export this certificate x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); var certData = x509Cert.Export(X509ContentType.Pfx); var convertedCert = new X509Certificate2(certData, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Attempts to move certificate to CCS UNC path try { // Create a stream out of that new certificate certData = convertedCert.Export(X509ContentType.Pfx, CCSCommonPassword); // Open UNC path and set path to certificate subject var filename = (CCSUncPath.EndsWith("/") ? CCSUncPath: CCSUncPath + "/") + x509Cert.GetNameInfo(X509NameType.SimpleName, false) + ".pfx"; var writer = new BinaryWriter(File.Open(filename, FileMode.Create)); writer.Write(certData); writer.Flush(); writer.Close(); // Certificate saved } catch (Exception ex) { // Log error Log.WriteError("SSLModuleService could not save certificate to Centralized Certificate Store", ex); // Re-throw throw; } } else { x509Cert = new X509Certificate2(certificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // Step 1: Register X.509 certificate in the store // Trying to keep X.509 store open as less as possible try { store.Open(OpenFlags.ReadWrite); store.Add(x509Cert); } catch (Exception ex) { Log.WriteError(String.Format("SSLModuleService could not import PFX into X509Store('{0}', '{1}')", store.Name, store.Location), ex); // Re-throw error throw; } finally { store.Close(); } } // Step 2: Instantiate a copy of new X.509 certificate try { newcert = GetSSLCertificateFromX509Certificate2(x509Cert); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, "SSLModuleService could not instantiate a copy of new X.509 certificate.", ex); } // Step 3: Remove old certificate from the web site if any try { // Check if certificate already exists, remove it. if (oldcert != null) { DeleteCertificate(oldcert, website); } } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, null, website, string.Format("SSLModuleService could not remove existing certificate from '{0}' web site.", website.Name), ex); } // Step 4: Register new certificate with HTTPS binding on the web site try { AddBinding(x509Cert, website); } catch (Exception ex) { HandleExceptionAndRollbackCertificate(store, x509Cert, oldcert, website, String.Format("SSLModuleService could not add new X.509 certificate to '{0}' web site.", website.Name), ex); } return newcert; }
public SSLCertificate GetCurrentSiteCertificate(WebSite website) { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); byte[] currentHash = sslbind.CertificateHash; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2 oldcertificate = (from X509Certificate2 c in store.Certificates where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(currentHash) select c).Single(); store.Close(); SSLCertificate certificate = new SSLCertificate(); certificate.Hash = oldcertificate.GetCertHash(); certificate.SerialNumber = oldcertificate.SerialNumber; return certificate; } }
private void HandleExceptionAndRollbackCertificate(X509Store store, X509Certificate2 x509Cert, SSLCertificate oldCert, WebSite webSite, string errorMessage, Exception ex) { if (!UseCCS) { try { // Rollback X.509 store changes store.Open(OpenFlags.ReadWrite); store.Remove(x509Cert); store.Close(); } catch (Exception) { Log.WriteError("SSLModuleService could not rollback and remove certificate from store", ex); } // Install old certificate back if any if (oldCert != null) InstallCertificate(oldCert, webSite); } // Log the error Log.WriteError(errorMessage + " All changes have been rolled back.", ex); // Re-throw throw ex; }
public void UpdateSite(WebSite site) { // ensure physical site content path if (String.IsNullOrEmpty(site.ContentPath)) throw new Exception("SiteContentPathEmpty"); // using (var srvman = GetServerManager()) { // var iisObject = srvman.Sites[site.Name]; // iisObject.Applications[0].ApplicationPoolName = site.ApplicationPool; // iisObject.Applications[0].VirtualDirectories[0].PhysicalPath = site.ContentPath; // iisObject.ServerAutoStart = true; // srvman.CommitChanges(); } }
public ResultObject DeleteCertificate(SSLCertificate certificate, WebSite website) { ResultObject result = new ResultObject(); try { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, false)[0]; store.Remove(cert); store.Close(); RemoveBinding(certificate, website); result.IsSuccess = true; } catch (Exception ex) { result.IsSuccess = false; result.AddError("", ex); } return result; }
private static bool SiteHasBindingWithDedicatedIp(ServerManager srvman, WebSite website) { try { var bindings = srvman.Sites[website.SiteId].Bindings; return bindings.Any(b => string.IsNullOrEmpty(b.Host) && b.BindingInformation.Split(':')[1] != "*"); } catch { return false; } }
static int Main(string[] args) { ResultCode resultCode = 0; // use a configuration file to list all the sites you want to check // provide SMTP server information too var version = Assembly.GetEntryAssembly().GetName().Version; string startup = "LINKCHECKER " + version + " (c) Ian Mercer 2010 http://blog.abodit.com"; Console.WriteLine(startup); Console.WriteLine("".PadLeft(startup.Length, '-')); Console.WriteLine(); if (!File.Exists("LinkChecker.ini")) { Console.WriteLine("Please reinstall, you need both the .EXE and the .INI file"); Console.WriteLine("See http://blog.abodit.com"); } IConfigSource mainSource = new IniConfigSource("LinkChecker.ini"); ArgvConfigSource argSource = new ArgvConfigSource(args); //argSource.AddSwitch("SMTP", "Server", "smtp"); //argSource.AddSwitch("SMTP", "Port", "port"); //argSource.AddSwitch("SMTP", "Username", "user"); //argSource.AddSwitch("SMTP", "Password", "password"); argSource.AddSwitch("Settings", "Domain", "d"); // a single domain argSource.AddSwitch("Settings", "Delay", "de"); // argSource.AddSwitch("Settings", "IncludeSelectors", "is"); // Exclude pages option argSource.AddSwitch("Settings", "ExcludeSelectors", "xs"); // Exclude pages option argSource.AddSwitch("Settings", "ExcludePages", "xp"); // Exclude pages option argSource.AddSwitch("Settings", "All", "a"); // argSource.AddSwitch("Settings", "Pages", "pa"); // argSource.AddSwitch("Settings", "Seo", "s"); // argSource.AddSwitch("Settings", "Changes", "c"); // argSource.AddSwitch("Settings", "Limit", "li"); // argSource.AddSwitch("Settings", "Dump", "du"); // dump all text found argSource.AddSwitch("Settings", "Suggestions", "su"); mainSource.Merge(argSource); //var SMTPConfig = mainSource.Configs["SMTP"]; var config = mainSource.Configs["Settings"]; //string SMTPServer = SMTPConfig.GetString("Server", ""); //int SMTPPort = SMTPConfig.GetInt("Port", 25); //string SMTPUsername = SMTPConfig.GetString("Username", ""); //string SMTPPassword = SMTPConfig.GetString("Password", ""); //SMTPConfig.Set("Server", SMTPServer); //SMTPConfig.Set("Port", SMTPPort); //SMTPConfig.Set("Username", SMTPUsername); //SMTPConfig.Set("Password", SMTPPassword); int delayBetween = config.GetInt("Delay", 10); config.Set("Delay", delayBetween); string excludedPathSetting = config.GetString("ExcludePages", ""); //""); // common duplicate pages / comments string excludedPaths = excludedPathSetting; config.Set("ExcludePages", excludedPaths); string includeSelector = config.GetString("IncludeSelectors", "head title,body"); string excludeSelector = config.GetString("ExcludeSelectors", ".pageHeader,#header,.header,#footer,.footer,#sidebar,.sidebar," + "#feedbackTab,#feedback,.feedback,#feedbackdialog," + "#smalltype,.share-links-footer,block-ec_blogs"); config.Set("IncludeSelector", includeSelector); config.Set("ExcludeSelector", excludeSelector); string listPages = config.GetString("Pages", "").ToLower(); if (listPages != "none" && listPages != "list") listPages = "error"; config.Set("Pages", listPages); string seo = config.GetString("Seo", "").ToLower(); if (seo != "none" && seo != "list") seo = "error"; config.Set("Seo", seo); string changes = config.GetString("Changes", "").ToLower(); if (changes != "none" && changes != "error") changes = "list"; config.Set("Changes", changes); int limit = config.GetInt("Limit", 3000); // 3000 pages limit by default string dumpFilePath = config.GetString("Dump"); if (dumpFilePath != null) config.Set("Dump", dumpFilePath); bool showSuggestedLinks = !string.IsNullOrWhiteSpace(config.Get("Suggestions", "")); config.Set("Suggestions", showSuggestedLinks); string domainSingle = config.GetString("Domain", ""); // Save any changes back to the config file // Don't do this because then they affect everyone after that ... //mainSource.Save(); if (string.IsNullOrWhiteSpace(domainSingle)) { Console.WriteLine(" Usage: linkchecker -d example.com"); Console.WriteLine(" Parameters:"); Console.WriteLine(" -d:example.com The domain or starting Url you wish to check"); Console.WriteLine(" all pages at the same level or below will be scanned"); Console.WriteLine(" -xp:path1,path2 Exclude any paths that include path1, path2, ..."); Console.WriteLine(" e.g. -xp:comment,/recommend,/email,/print"); Console.WriteLine(); Console.WriteLine(" -all Complete dump including pages, changes and errors (default)"); Console.WriteLine(" -pages:none|list|error Detailed information about page and links (default = error)"); Console.WriteLine(" -seo:none|list|error Information about any SEO issues (default = error)"); Console.WriteLine(" -changes:none|list|error Changes to pages or links since last run (default=list)"); Console.WriteLine(); Console.WriteLine(" -delay 10 Delay 10 seconds between pages (less load on server being tested)"); Console.WriteLine(" -limit 3000 Limit how many pages (3000 default)"); Console.WriteLine(); Console.WriteLine(" -dump filename Dump all content from pages to a file"); Console.WriteLine(" -xs:domSelector2,... Exclude DOM elements that match jQuery style selectors"); Console.WriteLine(" -is:domSelector1,... Include DOM elements that match jQuery style selectors"); Console.WriteLine(" e.g. -is:head title,body -xs:footer,#header,#sidebar,.comment"); Console.WriteLine(); Console.WriteLine(" -xs and -is are applied throughout the DOM tree to select elements"); Console.WriteLine(); Console.WriteLine(" You can put <meta linkedpages=\"\\url,\\url2,...\"> on any page to check that those links"); Console.WriteLine(" are present on the page somewhere. In effect a 'link contract' that the page must meet."); Console.WriteLine(" This allows you to check that none of the key links on your site are broken."); Console.WriteLine(); Console.WriteLine(" -suggestions Lists all the links that are on a page but not in a linkedpages meta tag"); Console.WriteLine(" e.g. <meta linkedpages=\"\\login,\\logout,\\home\">"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(" RESULT CODE is non-zero if there are any errors and you specified error on any element above"); //Console.WriteLine(" -smtp An SMTP server to email the results to"); //Console.WriteLine(" -port SMTP Server port (25)"); //Console.WriteLine(" -user SMTP Server user name"); //Console.WriteLine(" -password SMTP Server password"); Console.WriteLine(); Console.WriteLine(" Settings may also be placed in a file LinkChecker.ini"); Console.WriteLine(); Console.WriteLine(" An XML dump of your web site will be placed in a subdirectory and used for subsequent runs as a comparison"); Console.WriteLine(" to alert you when new pages appear or links get broken between pages on your site."); Console.WriteLine(); return 1; } int failed = 0; Console.WriteLine("Domain = " + (domainSingle ?? "null")); // Display the config settings to the user //if (!string.IsNullOrWhiteSpace(SMTPServer)) // Console.WriteLine("SMTP Server " + SMTPServer); string cleanDomain = domainSingle.Replace("http://", ""); Uri urlRoot = new Uri("http://" + cleanDomain); string directoryPath = System.IO.Path.Combine(Environment.CurrentDirectory, SafeFileName(cleanDomain)); if (!System.IO.Directory.Exists(directoryPath)) System.IO.Directory.CreateDirectory(directoryPath); string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH;mm") + ".xml"; string filePath = Path.Combine(directoryPath, fileName); // A web site or part of a web site, e.g. www.microsoft.com/presspass WebSite webSite = new WebSite(cleanDomain, delayBetween*1000) .Except(excludedPaths); // Collect error messages List<string> errorMessages = new List<string>(); // Collect SEO warnings List<string> seoWarnings = new List<string>(); // Look for duplicate titles Dictionary<string, int> titleCounts = new Dictionary<string, int>(); Console.WriteLine(" _______________________________________________________________________________________ "); int countdown = limit; foreach (var webPage in webSite.WebPages) { // Count only errors and good pages ... if ((!(webPage is WebPage.External) && !(webPage is WebPage.OtherContent)) && countdown-- < 0) { Console.WriteLine("Limit reached, use something more than -limit " + limit + ""); break; } Uri url = webPage.Url; if (webPage is WebPage.Internal) { WebPage.Internal webPageInternal = webPage as WebPage.Internal; if (listPages != "none") { Console.WriteLine(url); Console.WriteLine(" title = " + webPageInternal.Title); Console.WriteLine(" description = " + webPageInternal.MetaDescription); foreach (var message in webPageInternal.ErrorMessages) { string err = " ERROR ON PAGE = " + message; Console.WriteLine(err); } errorMessages.AddRange(webPageInternal.ErrorMessages); foreach (var message in webPageInternal.SeoWarnings) { string err = " WARNING = " + message; Console.WriteLine(err); } } errorMessages.AddRange(webPageInternal.ErrorMessages); seoWarnings.AddRange(webPageInternal.SeoWarnings); // Check for duplicates too string title = webPageInternal.Title ?? ""; if (titleCounts.ContainsKey(title)) titleCounts[title]++; else titleCounts.Add(title, 1); if (!string.IsNullOrWhiteSpace(dumpFilePath)) { var documentNode = webPageInternal.HtmlDocument.DocumentNode; //<td class="itm" style="text-align:left" nowrap><a href="/ESIG">ESIG</a></td> //<td class="dsc">Engineering Science Interactive Graphics</td> var includeSelected = documentNode.QuerySelectorAll(includeSelector).ToList(); var excludeSelected = documentNode.QuerySelectorAll(excludeSelector).ToList(); Func<HtmlNode, bool> includeFilter = node => includeSelected.Contains(node); Func<HtmlNode, bool> excludeFilter = node => excludeSelected.Contains(node); using (FileStream file = File.Open(dumpFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)) using (StreamWriter sw = new StreamWriter(file)) { sw.WriteLine(url); sw.WriteLine(" title = " + webPageInternal.Title); sw.WriteLine(" description = " + webPageInternal.MetaDescription); var selected = documentNode.InnerTextButJustTheTextBits(includeFilter, excludeFilter, false); var lines = selected.Split('\n', '\r') .Select(s => s.Replace('\t', ' ')) .Where(s => !string.IsNullOrWhiteSpace(s) && s.Length > 1); // ignore single character lines foreach (var line in lines) sw.WriteLine(line.Trim()); //var lines = webPageInternal.HtmlDocument.DocumentNode.InnerTextButJustTheTextBits(filterPredicate).Split('\n', '\r') // .Select(s => s.Replace('\t', ' ')) // .Where(s => !string.IsNullOrWhiteSpace(s) && s.Length>1); // ignore single character lines //foreach (var line in lines) // sw.WriteLine(line.Trim()); sw.WriteLine(" _______________________________________________________________________________________ "); } } } else if (webPage is WebPage.External || webPage is WebPage.OtherContent) { if (listPages != "none") { Console.WriteLine(webPage.ToString()); } } else if (webPage is WebPage.Error) { Console.WriteLine(webPage.ToString()); failed++; errorMessages.Add(webPage.ToString()); } else { throw new ApplicationException("Unexpected type " + webPage); } //if (showSuggestedLinks) //foreach (var suggestion in webPageInternal.SuggestedLinks) //{ // Console.WriteLine(@"Consider adding [LinkedPage(""" + suggestion + @""")]"); //} //int count = requiredLinks.Count(x => x.Value > 0); //if (count == 0 && requiredLinks.Count > 0) //{ // Console.WriteLine(" +++ all required links found on page"); //} //else //{ // foreach (var missingLink in requiredLinks.Where(x => x.Value > 0)) // { // Console.WriteLine(" **** MISSING LINK FROM " + url + " to " + missingLink); // failed++; // } //} if (listPages != "none") Console.WriteLine("|---------------------------------------------------------------------------------------|"); } // Save the results ... XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; //xmlWriterSettings.CheckCharacters = false; xmlWriterSettings.NewLineHandling = NewLineHandling.Entitize; // Serialize to disk DataContractSerializer serializer = new DataContractSerializer(typeof(WebSite), new[] {typeof(WebPage) , typeof(WebPage.Error) , typeof(WebPage.ExceptionError) , typeof(WebPage.External) , typeof(WebPage.Internal) , typeof(WebPage.LoadError) , typeof(WebPage.OtherContent) , typeof(WebPage.Timeout) , typeof(System.UriFormatException) // ick! ,typeof(WebLink) }); // Now compare that against the previous version var lastFile = Directory.EnumerateFiles(directoryPath).Select(f => new FileInfo(f)).OrderByDescending(d => d.CreationTimeUtc).FirstOrDefault(); WebSite previous = null; // Read the previous last file in if (lastFile != null) { try { using (XmlReader xmlReader = XmlReader.Create(new FileStream(lastFile.FullName, FileMode.Open, FileAccess.Read))) { previous = (WebSite)serializer.ReadObject(xmlReader); } } catch (System.Runtime.Serialization.SerializationException ex) // the one we expect { previous = null; Console.WriteLine(ex); resultCode = resultCode | ResultCode.PROGRAM_ERROR; } catch (Exception ex) // and for now, catch all others ... { previous = null; Console.WriteLine(ex); resultCode = resultCode | ResultCode.PROGRAM_ERROR; } } if (changes != "none") { Console.WriteLine(@"|------------------------------------COMPARISON-----------------------------------------|"); bool writeXML = true; // unless ... try { if (previous != null) { var changeLines = previous.StructureCompare(0, webSite).ToArray(); if (changeLines.Any()) { resultCode = resultCode | ResultCode.CHANGE_DETECTED; foreach (var s in changeLines) { Console.WriteLine(s); } } else { writeXML = false; Console.WriteLine("NO CHANGES DETECTED SINCE " + lastFile.CreationTime.ToShortDateString()); } } } catch (Exception ex) { Console.WriteLine("Please report: Error comparing " + ex.ToString()); } if (writeXML) { try { // And write the updates to a new file using (XmlWriter xmlWriter = XmlWriter.Create(new FileStream(filePath, FileMode.CreateNew), xmlWriterSettings)) { serializer.WriteObject(xmlWriter, webSite); } } catch (Exception ex) { Console.WriteLine("Failed to write file " + ex.Message); } } } if (errorMessages.Count > 0) { resultCode = resultCode | ResultCode.PAGE_ERROR; Console.WriteLine(@"|-------------------------------------ERRORS " + errorMessages.Count() + "-----------------------------------------|"); foreach (var err in errorMessages) { Console.WriteLine(err); } } else { Console.WriteLine("No errors"); } // Find duplicate page titles var duplicatePageTitles = titleCounts.Where(x => x.Value > 1).ToList(); foreach (var duplicatePageTitle in duplicatePageTitles) { seoWarnings.Add("Duplicate title '" + duplicatePageTitle.Key + "' on " + duplicatePageTitle.Value + " pages"); } if (seo != "none") { if (seoWarnings.Any()) { if (seo == "error") resultCode = resultCode | ResultCode.SEO_ERROR; Console.WriteLine(@"|------------------------------------SEO WARNINGS (" + seoWarnings.Count() + ")------------------------------------|"); foreach (var err in seoWarnings) { Console.WriteLine(err); } } } Console.WriteLine(@"\_______________________________________________________________________________________/"); Console.WriteLine(); //Console.ReadKey(); // Now decide whether to fail or not ... if (resultCode > 0) { Console.WriteLine("**** FAILED WITH ERROR CODE ****"); if ((resultCode & ResultCode.CHANGE_DETECTED) != 0) Console.WriteLine(" Changes detected"); if ((resultCode & ResultCode.LINK_ERROR) != 0) Console.WriteLine(" Link error"); if ((resultCode & ResultCode.PAGE_ERROR) != 0) Console.WriteLine(" Page error"); if ((resultCode & ResultCode.PROGRAM_ERROR) != 0) Console.WriteLine(" Program error"); if ((resultCode & ResultCode.SEO_ERROR) != 0) Console.WriteLine(" SEO error"); } if (Environment.MachineName == "XPS") Thread.Sleep(20000); return (int)resultCode; }
/// <summary> /// Create a new WebSite object. /// </summary> /// <param name="id">Initial value of Id.</param> public static WebSite CreateWebSite(long id) { WebSite webSite = new WebSite(); webSite.Id = id; return webSite; }
public SSLCertificate ImportCertificate(WebSite website) { SSLCertificate certificate = new SSLCertificate { Success = false }; try { using (ServerManager sm = GetServerManager()) { Site site = sm.Sites[website.SiteId]; Binding sslbind = (from b in site.Bindings where b.Protocol == "https" select b).Single(); certificate.Hash = sslbind.CertificateHash; X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); X509Certificate2 x509Cert = (from X509Certificate2 c in store.Certificates where Convert.ToBase64String(c.GetCertHash()) == Convert.ToBase64String(certificate.Hash) select c).Single(); store.Close(); certificate.Hostname = x509Cert.GetNameInfo(X509NameType.SimpleName, false); certificate.FriendlyName = x509Cert.FriendlyName; certificate.CSRLength = Convert.ToInt32(x509Cert.PublicKey.Key.KeySize.ToString()); certificate.Installed = true; certificate.DistinguishedName = x509Cert.Subject; certificate.Hash = x509Cert.GetCertHash(); certificate.SerialNumber = x509Cert.SerialNumber; certificate.ExpiryDate = DateTime.Parse(x509Cert.GetExpirationDateString()); certificate.ValidFrom = DateTime.Parse(x509Cert.GetEffectiveDateString()); certificate.Success = true; } } catch (Exception ex) { certificate.Success = false; certificate.Certificate = ex.ToString(); } return certificate; }