public ArrayList GetPortalAliasArrayByPortalID(int PortalID) { IDataReader dr = DotNetNuke.Data.DataProvider.Instance().GetPortalAliasByPortalID(PortalID); try { ArrayList arr = new ArrayList(); while (dr.Read()) { PortalAliasInfo objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]); objPortalAliasInfo.PortalID = Convert.ToInt32(dr["PortalID"]); objPortalAliasInfo.HTTPAlias = Convert.ToString(dr["HTTPAlias"]).ToLower(); arr.Add(objPortalAliasInfo); } return(arr); } finally { if (dr != null) { dr.Close(); } } }
public PortalAliasCollection GetPortalAliasByPortalID(int PortalID) { IDataReader dr = DotNetNuke.Data.DataProvider.Instance().GetPortalAliasByPortalID(PortalID); try { PortalAliasCollection objPortalAliasCollection = new PortalAliasCollection(); while (dr.Read()) { PortalAliasInfo objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]); objPortalAliasInfo.PortalID = Convert.ToInt32(dr["PortalID"]); objPortalAliasInfo.HTTPAlias = Convert.ToString(dr["HTTPAlias"]); objPortalAliasCollection.Add(Convert.ToString(dr["HTTPAlias"]).ToLower(), objPortalAliasInfo); } return(objPortalAliasCollection); } finally { if (dr != null) { dr.Close(); } } }
/// <summary> /// Gets the portal alias by portal. /// </summary> /// <param name="portalId">The portal id.</param> /// <param name="portalAlias">The portal alias.</param> /// <returns>Portal alias.</returns> public static string GetPortalAliasByPortal(int portalId, string portalAlias) { string retValue = ""; //get the portal alias collection from the cache PortalAliasCollection portalAliasCollection = GetPortalAliasLookup(); string httpAlias; bool foundAlias = false; //Do a specified PortalAlias check first PortalAliasInfo objPortalAliasInfo = portalAliasCollection[portalAlias.ToLower()]; if (objPortalAliasInfo != null) { if (objPortalAliasInfo.PortalID == portalId) { //set the alias retValue = objPortalAliasInfo.HTTPAlias; foundAlias = true; } } if (!foundAlias) { //searching from longest to shortest alias ensures that the most specific portal is matched first //In some cases this method has been called with "portalaliases" that were not exactly the real portal alias //the startswith behaviour is preserved here to support those non-specific uses IEnumerable <String> aliases = portalAliasCollection.Keys.Cast <String>().OrderByDescending(k => k.Length); foreach (var currentAlias in aliases) { // check if the alias key starts with the portal alias value passed in - we use // StartsWith because child portals are redirected to the parent portal domain name // eg. child = 'www.domain.com/child' and parent is 'www.domain.com' // this allows the parent domain name to resolve to the child alias ( the tabid still identifies the child portalid ) objPortalAliasInfo = portalAliasCollection[currentAlias]; httpAlias = objPortalAliasInfo.HTTPAlias.ToLower(); if (httpAlias.StartsWith(portalAlias.ToLower()) && objPortalAliasInfo.PortalID == portalId) { retValue = objPortalAliasInfo.HTTPAlias; break; } if (httpAlias.StartsWith("www.")) { httpAlias = httpAlias.Replace("www.", ""); } else { httpAlias = string.Concat("www.", httpAlias); } if (httpAlias.StartsWith(portalAlias.ToLower()) && objPortalAliasInfo.PortalID == portalId) { retValue = objPortalAliasInfo.HTTPAlias; break; } } } return(retValue); }
/// ----------------------------------------------------------------------------- /// <summary> /// The PortalSettings Constructor encapsulates all of the logic /// necessary to obtain configuration settings necessary to render /// a Portal Tab view for a given request. /// </summary> /// <remarks> /// </remarks> /// <param name="tabId">The current tab</param> /// <param name="portalAliasInfo">The current portal</param> /// ----------------------------------------------------------------------------- public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) { PortalId = portalAliasInfo.PortalID; PortalAlias = portalAliasInfo; var portal = PortalController.Instance.GetPortal(portalAliasInfo.PortalID); BuildPortalSettings(tabId, portal); }
/// <summary> /// Generate WebAPI Links compatible with DNN Services Framework /// </summary> /// <param name="urlHelper">The UrlHelper</param> /// <param name="moduleFolderName">ModuleFolderName for the route</param> /// <param name="routeName">RouteName for the route</param> /// <param name="routeValues">Values to be passed to the route</param> /// <param name="portalAliasInfo">The PortalAlias to use in the Url </param> /// <returns>a url</returns> public static string DnnLink(this UrlHelper urlHelper, string moduleFolderName, string routeName, object routeValues, PortalAliasInfo portalAliasInfo) { var parm = new PortalAliasRouteManager(); var fullName = parm.GetRouteName(moduleFolderName, routeName, PortalController.Instance.GetCurrentPortalSettings().PortalAlias); HttpRouteValueDictionary allRouteValues = parm.GetAllRouteValues(portalAliasInfo, routeValues); return urlHelper.Link(fullName, allRouteValues); }
/// ----------------------------------------------------------------------------- /// <summary> /// The PortalSettings Constructor encapsulates all of the logic /// necessary to obtain configuration settings necessary to render /// a Portal Tab view for a given request. /// </summary> /// <remarks> /// </remarks> /// <param name="tabId">The current tab</param> /// <param name="portalAliasInfo">The current portal</param> /// ----------------------------------------------------------------------------- public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) { PortalId = portalAliasInfo.PortalID; PortalAlias = portalAliasInfo; var portal = string.IsNullOrEmpty(portalAliasInfo.CultureCode) ? PortalController.Instance.GetPortal(portalAliasInfo.PortalID) : PortalController.Instance.GetPortal(portalAliasInfo.PortalID, portalAliasInfo.CultureCode); BuildPortalSettings(tabId, portal); }
/// <summary> /// Gets the portal alias lookup. /// </summary> /// <param name="httpAlias">The alias.</param> /// <returns>Porta lAlias Info</returns> public static PortalAliasInfo GetPortalAliasLookup(string httpAlias) { PortalAliasInfo alias = null; var aliases = TestablePortalAliasController.Instance.GetPortalAliases(); if (aliases.ContainsKey(httpAlias)) { alias = TestablePortalAliasController.Instance.GetPortalAliases()[httpAlias]; } return(alias); }
/// <summary> /// Updates the portal alias info. /// </summary> /// <param name="objPortalAliasInfo">The obj portal alias info.</param> public void UpdatePortalAliasInfo(PortalAliasInfo objPortalAliasInfo) { DataCache.RemoveCache(DataCache.PortalAliasCacheKey); DataProvider.Instance().UpdatePortalAliasInfo(objPortalAliasInfo.PortalAliasID, objPortalAliasInfo.PortalID, objPortalAliasInfo.HTTPAlias.ToLower().Trim('/'), UserController.GetCurrentUserInfo().UserID); var objEventLog = new EventLogController(); objEventLog.AddLog(objPortalAliasInfo, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PORTALALIAS_UPDATED); }
public PortalAliasInfo(PortalAliasInfo alias) { this.HTTPAlias = alias.HTTPAlias; this.PortalAliasID = alias.PortalAliasID; this.PortalID = alias.PortalID; this.IsPrimary = alias.IsPrimary; this.Redirect = alias.Redirect; this.BrowserType = alias.BrowserType; this.CultureCode = alias.CultureCode; this.Skin = alias.Skin; }
public override void SetUp() { base.SetUp(); UpdateTabName(_tabId, "About Us"); CacheController.FlushPageIndexFromCache(); GetDefaultAlias(); _redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", PortalId, "CANONICALURL"); _primaryAlias = null; _customLocale = null; }
public PortalAliasInfo(PortalAliasInfo alias) { HTTPAlias = alias.HTTPAlias; PortalAliasID = alias.PortalAliasID; PortalID = alias.PortalID; IsPrimary = alias.IsPrimary; Redirect = alias.Redirect; BrowserType = alias.BrowserType; CultureCode = alias.CultureCode; Skin = alias.Skin; }
public void DeletePortalAlias(PortalAliasInfo portalAlias) { //Delete Alias DataProvider.Instance().DeletePortalAlias(portalAlias.PortalAliasID); //Log Event LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_DELETED); //clear portal alias cache ClearCache(false, portalAlias.PortalID); }
public PortalAliasInfo(PortalAliasInfo alias) { this.HttpAlias = alias.HttpAlias; this.PortalAliasId = alias.PortalAliasId; this.PortalId = alias.PortalId; this.IsPrimary = alias.IsPrimary; this.Redirect = alias.Redirect; ((IPortalAliasInfo)this).BrowserType = ((IPortalAliasInfo)alias).BrowserType; this.CultureCode = alias.CultureCode; this.Skin = alias.Skin; }
/// <summary> /// Adds the portal alias. /// </summary> /// <param name="objPortalAliasInfo">The obj portal alias info.</param> /// <returns>Portal alias id.</returns> public int AddPortalAlias(PortalAliasInfo objPortalAliasInfo) { int Id = DataProvider.Instance().AddPortalAlias(objPortalAliasInfo.PortalID, objPortalAliasInfo.HTTPAlias.ToLower().Trim('/'), UserController.GetCurrentUserInfo().UserID); var objEventLog = new EventLogController(); objEventLog.AddLog(objPortalAliasInfo, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", EventLogController.EventLogType.PORTALALIAS_CREATED); //clear portal alias cache DataCache.RemoveCache(DataCache.PortalAliasCacheKey); ServicesRoutingManager.ReRegisterServiceRoutesWhileSiteIsRunning(); return(Id); }
protected static void AutoAddAlias(HttpContext context) { var portalId = Host.Host.HostPortalID; //the domain name was not found so try using the host portal's first alias if (portalId > Null.NullInteger) { var portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = Globals.GetDomainName(context.Request, true) }; PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); context.Response.Redirect(context.Request.Url.ToString(), true); } }
public void UpdatePortalAlias(PortalAliasInfo portalAlias) { //Update Alias DataProvider.Instance().UpdatePortalAliasInfo(portalAlias.PortalAliasID, portalAlias.PortalID, portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), portalAlias.CultureCode, portalAlias.Skin, portalAlias.BrowserType.ToString(), portalAlias.IsPrimary, UserController.Instance.GetCurrentUserInfo().UserID); //Log Event LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_UPDATED); //clear portal alias cache ClearCache(false); }
/// <summary> /// Gets the portal alias by portal. /// </summary> /// <param name="portalId">The portal id.</param> /// <param name="portalAlias">The portal alias.</param> /// <returns>Portal alias.</returns> public static string GetPortalAliasByPortal(int portalId, string portalAlias) { string retValue = string.Empty; bool foundAlias = false; PortalAliasInfo portalAliasInfo = Instance.GetPortalAlias(portalAlias, portalId); if (portalAliasInfo != null) { retValue = portalAliasInfo.HTTPAlias; foundAlias = true; } if (!foundAlias) { // searching from longest to shortest alias ensures that the most specific portal is matched first // In some cases this method has been called with "portalaliases" that were not exactly the real portal alias // the startswith behaviour is preserved here to support those non-specific uses var controller = new PortalAliasController(); var portalAliases = controller.GetPortalAliasesInternal(); var portalAliasCollection = portalAliases.OrderByDescending(k => k.Key.Length); foreach (var currentAlias in portalAliasCollection) { // check if the alias key starts with the portal alias value passed in - we use // StartsWith because child portals are redirected to the parent portal domain name // eg. child = 'www.domain.com/child' and parent is 'www.domain.com' // this allows the parent domain name to resolve to the child alias ( the tabid still identifies the child portalid ) string httpAlias = currentAlias.Value.HTTPAlias.ToLowerInvariant(); if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) { retValue = currentAlias.Value.HTTPAlias; break; } httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && currentAlias.Value.PortalID == portalId) { retValue = currentAlias.Value.HTTPAlias; break; } } } return(retValue); }
public HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues) { var allRouteValues = new HttpRouteValueDictionary(routeValues); var segments = portalAliasInfo.HTTPAlias.Split('/'); if(segments.Length > 1) { for(int i = 1; i < segments.Length; i++) { var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); var value = segments[i]; allRouteValues.Add(key, value); } } return allRouteValues; }
public int AddPortalAlias(PortalAliasInfo portalAlias) { //Add Alias int Id = _dataProvider.AddPortalAlias(portalAlias.PortalID, portalAlias.HTTPAlias.ToLower().Trim('/'), portalAlias.CultureCode, portalAlias.Skin, portalAlias.BrowserType.ToString(), portalAlias.IsPrimary, UserController.Instance.GetCurrentUserInfo().UserID); //Log Event LogEvent(portalAlias, EventLogController.EventLogType.PORTALALIAS_CREATED); //clear portal alias cache ClearCache(true); return(Id); }
/// <summary> /// Gets the portal alias array by portal ID. /// </summary> /// <param name="PortalID">The portal ID.</param> /// <returns>Portal alias list.</returns> public ArrayList GetPortalAliasArrayByPortalID(int PortalID) { IDataReader dr = DataProvider.Instance().GetPortalAliasByPortalID(PortalID); try { var arr = new ArrayList(); while (dr.Read()) { var objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]); objPortalAliasInfo.PortalID = Convert.ToInt32(dr["PortalID"]); objPortalAliasInfo.HTTPAlias = Convert.ToString(dr["HTTPAlias"]).ToLower(); arr.Add(objPortalAliasInfo); } return(arr); } finally { CBO.CloseDataReader(dr, true); } }
public PortalAliasCollection GetPortalAliasByPortalID(int PortalID) { IDataReader dr = DotNetNuke.Data.DataProvider.Instance().GetPortalAliasByPortalID(PortalID); try { PortalAliasCollection objPortalAliasCollection = new PortalAliasCollection(); while (dr.Read()) { PortalAliasInfo objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]); objPortalAliasInfo.PortalID = Convert.ToInt32(dr["PortalID"]); objPortalAliasInfo.HTTPAlias = Convert.ToString(dr["HTTPAlias"]); objPortalAliasCollection.Add(Convert.ToString(dr["HTTPAlias"]).ToLower(), objPortalAliasInfo); } return objPortalAliasCollection; } finally { if (dr != null) { dr.Close(); } } }
public ArrayList GetPortalAliasArrayByPortalID(int PortalID) { IDataReader dr = DotNetNuke.Data.DataProvider.Instance().GetPortalAliasByPortalID(PortalID); try { ArrayList arr = new ArrayList(); while (dr.Read()) { PortalAliasInfo objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]); objPortalAliasInfo.PortalID = Convert.ToInt32(dr["PortalID"]); objPortalAliasInfo.HTTPAlias = Convert.ToString(dr["HTTPAlias"]).ToLower(); arr.Add(objPortalAliasInfo); } return arr; } finally { if (dr != null) { dr.Close(); } } }
/// <summary> /// Gets the portal aliases. /// </summary> /// <returns>Portal alias collection.</returns> public PortalAliasCollection GetPortalAliases() { IDataReader dr = DataProvider.Instance().GetPortalAliasByPortalID(-1); try { var portalAliasCollection = new PortalAliasCollection(); while (dr.Read()) { var objPortalAliasInfo = new PortalAliasInfo { PortalAliasID = Convert.ToInt32(dr["PortalAliasID"]), PortalID = Convert.ToInt32(dr["PortalID"]), HTTPAlias = Convert.ToString(dr["HTTPAlias"]) }; portalAliasCollection.Add(Convert.ToString(dr["HTTPAlias"]).ToLower(), objPortalAliasInfo); } return(portalAliasCollection); } finally { CBO.CloseDataReader(dr, true); } }
public string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias) { return GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(portalAlias.HTTPAlias)); }
public void AdvancedUrlProvider_PrimaryPortalAlias(Dictionary<string, string> testFields) { string defaultAlias = testFields["DefaultAlias"]; string redirectMode = testFields["RedirectMode"]; var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", "PrimaryPortalAlias"); string language = testFields["Language"].Trim(); if (!String.IsNullOrEmpty(language)) { _customLocale = new Locale { Code = language, Fallback = "en-US" }; _customLocale.Text = CultureInfo.CreateSpecificCulture(_customLocale.Code).NativeName; Localization.SaveLanguage(_customLocale); Localization.AddLanguageToPortals(_customLocale.LanguageId); //add new primary alias _primaryAlias = new PortalAliasInfo { PortalID = PortalId, HTTPAlias = defaultAlias, CultureCode = language, IsPrimary = true }; _primaryAlias.PortalAliasID = PortalAliasController.Instance.AddPortalAlias(_primaryAlias); } else { SetDefaultAlias(defaultAlias); } PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", redirectMode); ExecuteTest("Improved", settings, testFields); }
public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, NameValueCollection queryStringCol, FriendlyUrlOptions options, out string redirectLocation, ref List <string> messages) { bool doRedirect = false; redirectLocation = "";//set blank location //compare to known pattern of old Urls string path = requestUri.AbsoluteUri; if (string.IsNullOrEmpty(path) == false && Regex.IsMatch(path, @"(^|/)(mid|moduleId)/\d+/?", RegexOptions.IgnoreCase) == false) { //could be in old /groupId/xx format - if so, we want to redirect it Regex pathRegex = new Regex(@"/groupid/(?<groupid>\d+)", RegexOptions.IgnoreCase); Match pathMatch = pathRegex.Match(path); if (pathMatch.Success) { string groupIdRaw = pathMatch.Groups["groupid"].Value; int groupId; if (int.TryParse(groupIdRaw, out groupId)) { //ok, valid item Id found //get the valid Url for this item Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(portalid, this, options); //look up the friendly url index using the item key string furlKey = FriendlyUrlInfo.MakeKey("group", groupId); if (friendlyUrlIndex != null) { string friendlyUrl = null; TabController tc = new TabController(); TabInfo tab = tc.GetTab(tabId, portalid, false); if (tab != null && tab.ParentId == GroupPagePathTabId) { //this is the child tab of the group tab string cpFurlKey = "t" + tabId.ToString() + furlKey; friendlyUrl = (string)friendlyUrlIndex[cpFurlKey]; } if (friendlyUrl == null) { friendlyUrl = (string)friendlyUrlIndex[furlKey]; } if (friendlyUrl != null) { //ok, we're going to replace this in the Url if (HideGroupPagePath == false) { friendlyUrl = base.EnsureLeadingChar("/", friendlyUrl); string result = pathRegex.Replace(path, friendlyUrl); doRedirect = true; redirectLocation = result; } else { DotNetNuke.Entities.Portals.PortalAliasInfo pa = DotNetNuke.Entities.Portals.PortalAliasController.GetPortalAliasInfo(httpAlias); if (pa != null) { DotNetNuke.Entities.Portals.PortalSettings ps = new DotNetNuke.Entities.Portals.PortalSettings(tabId, pa); redirectLocation = DotNetNuke.Common.Globals.NavigateURL(tabId, ps, "", "groupid=" + groupId); doRedirect = true; } } } } } } } return(doRedirect); }
private static OrderedDictionary BuildPortalAliasesRegexDictionary() { IDictionary<string, PortalAliasInfo> aliases = TestablePortalAliasController.Instance.GetPortalAliases(); //create a new OrderedDictionary. We use this because we //want to key by the correct regex pattern and return the //portalAlias that matches, and we want to preserve the //order of the items, such that the item with the most path separators (/) //is at the front of the list. var regexList = new OrderedDictionary(aliases.Count); //this regex pattern, when formatted with the httpAlias, will match a request //for this portalAlias const string aliasRegexPattern = @"(?:^(?<http>http[s]{0,1}://){0,1})(?:(?<alias>_ALIAS_)(?<path>$|\?[\w]*|/[\w]*))"; var pathLengths = new List<int>(); foreach (string aliasKey in aliases.Keys) { PortalAliasInfo alias = aliases[aliasKey]; //regex escape the portal alias for inclusion into a regex pattern string plainAlias = alias.HTTPAlias; string escapedAlias = Regex.Escape(plainAlias); var aliasesToAdd = new List<string> { escapedAlias }; //check for existence of www. version of domain, if it doesn't have a www. if (plainAlias.ToLower().StartsWith("www.")) { if (plainAlias.Length > 4) { string noWWWVersion = plainAlias.Substring(4); if (!aliases.ContainsKey(noWWWVersion)) { //there is no no-www version of the alias aliasesToAdd.Add(Regex.Escape(noWWWVersion)); } } } else { string wwwVersion = "www." + plainAlias; if (!aliases.ContainsKey(wwwVersion)) { aliasesToAdd.Add(Regex.Escape(wwwVersion)); } } int count = 0; foreach (string aliasToAdd in aliasesToAdd) { //set flag on object to know whether to redirect or not count++; var aliasObject = new PortalAliasInfo(alias) { Redirect = count != 1 }; //format up the regex pattern by replacing the alias portion with the portal alias name string regexPattern = aliasRegexPattern.Replace("_ALIAS_", aliasToAdd); //work out how many path separators there are in the portalAlias (ie myalias/mychild = 1 path) int pathLength = plainAlias.Split('/').GetUpperBound(0); //now work out where in the list we should put this portalAlias regex pattern //the list is to be sorted so that those aliases with the most paths //are at the front of the list : ie, they are tested first int insertPoint = pathLengths.Count - 1; //walk through the existing list of path lengths, //and ascertain where in the list this one falls //if they are all the same path length, then place them in portal alias order for (int i = 0; i < pathLengths.Count; i++) { insertPoint = i; if (pathLength > pathLengths[i]) { //larger than this position, insert at this value break; } insertPoint++; //next one along (if at end, means add) } if (pathLengths.Count > 0 && insertPoint <= pathLengths.Count - 1) { //put the new regex pattern into the correct position regexList.Insert(insertPoint, regexPattern, aliasObject); pathLengths.Insert(insertPoint, pathLength); } else { //put the new regex pattern on the end of the list regexList.Add(regexPattern, aliasObject); pathLengths.Add(pathLength); } } } return regexList; }
public override void SetUp() { base.SetUp(); DeleteTab(_testPage); CreateTab(_testPage); UpdateTabName(_tabId, "About Us"); UpdateTabSkin(_tabId, ""); CacheController.FlushPageIndexFromCache(); GetDefaultAlias(); _redirectMode = PortalController.GetPortalSetting("PortalAliasMapping", PortalId, "CANONICALURL"); _sslEnforced = PortalController.GetPortalSettingAsBoolean("SSLEnforced", PortalId, false); _sslEnabled = PortalController.GetPortalSettingAsBoolean("SSLEnabled", PortalId, false); _primaryAlias = null; _customLocale = null; DataCache.ClearCache(); }
/// <summary> /// Adds an entry to the collection. /// </summary> public void Add(String key, PortalAliasInfo value) { Dictionary.Add(key, value); }
protected string AddPortalAlias(string portalAlias, int portalID) { if (!String.IsNullOrEmpty(portalAlias)) { if (portalAlias.IndexOf("://") != -1) { portalAlias = portalAlias.Remove(0, portalAlias.IndexOf("://") + 3); } var objPortalAliasController = new PortalAliasController(); var objPortalAlias = objPortalAliasController.GetPortalAlias(portalAlias, portalID); if (objPortalAlias == null) { objPortalAlias = new PortalAliasInfo { PortalID = portalID, HTTPAlias = portalAlias }; objPortalAliasController.AddPortalAlias(objPortalAlias); } } return portalAlias; }
private static string MakeUrlWithAlias(Uri requestUri, PortalAliasInfo alias) { return MakeUrlWithAlias(requestUri, alias.HTTPAlias); }
private static void LogEvent(PortalAliasInfo portalAlias, EventLogController.EventLogType logType) { int userId = UserController.Instance.GetCurrentUserInfo().UserID; EventLogController.Instance.AddLog(portalAlias, PortalController.Instance.GetCurrentPortalSettings(), userId, "", logType); }
public void UpdatePortalAliasInfo(PortalAliasInfo portalAlias) { TestablePortalAliasController.Instance.UpdatePortalAlias(portalAlias); }
/// <summary> /// Creates a new portal alias /// </summary> /// <param name="PortalId">Id of the portal</param> /// <param name="PortalAlias">Portal Alias to be created</param> /// <history> /// [cnurse] 01/11/2005 created /// </history> public void AddPortalAlias( int PortalId, string PortalAlias ) { PortalAliasController objPortalAliasController = new PortalAliasController(); //Check if the Alias exists PortalAliasInfo objPortalAliasInfo = objPortalAliasController.GetPortalAlias( PortalAlias, PortalId ); //If alias does not exist add new if( objPortalAliasInfo == null ) { objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalID = PortalId; objPortalAliasInfo.HTTPAlias = PortalAlias; objPortalAliasController.AddPortalAlias( objPortalAliasInfo ); } }
protected string AddPortalAlias(string portalAlias, int portalID) { if (!String.IsNullOrEmpty(portalAlias)) { if (portalAlias.IndexOf("://", StringComparison.Ordinal) != -1) { portalAlias = portalAlias.Remove(0, portalAlias.IndexOf("://", StringComparison.Ordinal) + 3); } var alias = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalID); if (alias == null) { alias = new PortalAliasInfo { PortalID = portalID, HTTPAlias = portalAlias }; PortalAliasController.Instance.AddPortalAlias(alias); } } return portalAlias; }
/// <summary> /// Returns a ChosenPortalAlias object where the portalId, culture code and isMobile matches /// </summary> /// <param name="aliases"></param> /// <param name="portalId"></param> /// <param name="result"></param> /// <param name="cultureCode"></param> /// <param name="browserType"></param> /// <returns>A ChosenPOrtalAlias</returns> /// <remarks>Note will return a best-match by portal if no specific culture Code match found</remarks> public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable <PortalAliasInfo> aliases, int portalId, UrlAction result, string cultureCode, BrowserTypes browserType) { var aliasList = aliases.ToList(); //First check if our current alias is already a perfect match. PortalAliasInfo foundAlias = null; if (result != null && !string.IsNullOrEmpty(result.HttpAlias)) { //try to find exact match foundAlias = aliasList.FirstOrDefault(a => a.BrowserType == browserType && (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0) && a.PortalID == portalId && a.HTTPAlias == result.HttpAlias); if (foundAlias == null) //let us try again using Startswith() to find matching Hosts { foundAlias = aliasList.FirstOrDefault(a => a.BrowserType == browserType && (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0) && a.PortalID == portalId && a.HTTPAlias.StartsWith(result.HttpAlias.Split('/')[0])); } } //27138 : Redirect loop caused by duplicate primary aliases. Changed to only check by browserType/Culture code which makes a primary alias if (foundAlias == null) { foundAlias = aliasList.Where(a => a.BrowserType == browserType && (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || String.IsNullOrEmpty(a.CultureCode)) && a.PortalID == portalId) .OrderByDescending(a => a.IsPrimary) .ThenByDescending(a => a.CultureCode) .FirstOrDefault(); } //JIRA DNN-4882 : DevPCI fix bug with url Mobile -> Search alias with culture code // START DNN-4882 if (foundAlias == null) { foundAlias = aliasList.Where(a => (String.Compare(a.CultureCode, cultureCode, StringComparison.OrdinalIgnoreCase) == 0 || String.IsNullOrEmpty(a.CultureCode)) && a.PortalID == portalId) .OrderByDescending(a => a.IsPrimary) .ThenByDescending(a => a.CultureCode) .FirstOrDefault(); } // END DNN-4882 if (foundAlias != null) { if (result != null && result.PortalAlias != null) { if (foundAlias.BrowserType != result.PortalAlias.BrowserType) { result.Reason = foundAlias.CultureCode != result.PortalAlias.CultureCode ? RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser : RedirectReason.Wrong_Portal_Alias_For_Browser_Type; } else { if (foundAlias.CultureCode != result.PortalAlias.CultureCode) { result.Reason = RedirectReason.Wrong_Portal_Alias_For_Culture; } } } } else { // if we didn't find a specific match, return the default, which is the closest match var defaultAlias = aliasList .Where(a => a.PortalID == portalId) .OrderByDescending(a => a.IsPrimary) .FirstOrDefault(); foundAlias = defaultAlias; } return(foundAlias); }
public PortalAliasInfo(PortalAliasInfo alias) : this((IPortalAliasInfo)alias) { }
protected abstract void GetPortalAliasProperties(int index, PortalAliasInfo portalAlias);
/// ----------------------------------------------------------------------------- /// <summary> /// The PortalSettings Constructor encapsulates all of the logic /// necessary to obtain configuration settings necessary to render /// a Portal Tab view for a given request. /// </summary> /// <remarks> /// </remarks> /// <param name="tabID">The current tab</param> /// <param name="objPortalAliasInfo">The current portal</param> /// <history> /// [cnurse] 10/21/2004 documented /// </history> /// ----------------------------------------------------------------------------- public PortalSettings(int tabID, PortalAliasInfo objPortalAliasInfo) { ActiveTab = new TabInfo(); PortalId = objPortalAliasInfo.PortalID; PortalAlias = objPortalAliasInfo; var portal = PortalController.Instance.GetPortal(PortalId); if (portal != null) { GetPortalSettings(tabID, portal); } }
// Adds an entry to the collection. public void Add(string key, PortalAliasInfo value) { this.Dictionary.Add(key, value); } //Add
public int AddPortalAlias(PortalAliasInfo portalAlias) { return TestablePortalAliasController.Instance.AddPortalAlias(portalAlias); }
public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, PortalAliasInfo portalAlias, ref List<string> messages, out int status, out string location) { throw new NotImplementedException(); }
protected void AddAlias(object sender, EventArgs e) { //Add a new empty rule and set the editrow to the new row var portalAlias = new PortalAliasInfo { PortalID = CurrentPortalId }; Aliases.Add(portalAlias); Grid.EditItemIndex = Aliases.Count - 1; //Set the AddMode to true AddMode = true; //Rebind the collection BindAliases(); }
public int AddPortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).AddPortalAlias(portalAlias);
private static void AddLanguageHttpAlias(int portalId, Locale locale) { if (Config.GetFriendlyUrlProvider() == "advanced") { // create new HTTPAlias for language var portalInfo = PortalController.Instance.GetPortal(portalId); PortalAliasInfo currentAlias = null; string httpAlias = null; var portalAliasses = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); var portalAliasInfos = portalAliasses as IList<PortalAliasInfo> ?? portalAliasses.ToList(); if (portalAliasses != null && portalAliasInfos.Any()) { currentAlias = portalAliasInfos.First(); httpAlias = currentAlias.HTTPAlias; } if (currentAlias != null && !string.IsNullOrEmpty(httpAlias) && portalInfo != null) { if (!string.IsNullOrEmpty(currentAlias.CultureCode)) { // the portal alias is culture specific if (currentAlias.CultureCode == portalInfo.CultureCode) { // remove the culture from the alias httpAlias = httpAlias.Substring(0, httpAlias.LastIndexOf("/", StringComparison.Ordinal)); } } var alias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()); if (!String.IsNullOrEmpty(alias)) { var newAlias = new PortalAliasInfo(currentAlias) { IsPrimary = true, CultureCode = locale.Code, HTTPAlias = GetValidLanguageURL(portalId, httpAlias, locale.Code.ToLowerInvariant()) }; PortalAliasController.Instance.AddPortalAlias(newAlias); } } } }
public void DeletePortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).DeletePortalAlias(portalAlias);
public void AdvancedUrlRewriter_PrimaryPortalAlias(Dictionary<string, string> testFields) { string defaultAlias = testFields["DefaultAlias"]; var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"]); settings.PortalId = PortalId; string language = testFields["Language"].Trim(); string skin = testFields["Skin"].Trim(); if (!String.IsNullOrEmpty(language)) { _customLocale = new Locale { Code = language, Fallback = "en-US" }; _customLocale.Text = CultureInfo.CreateSpecificCulture(_customLocale.Code).NativeName; Localization.SaveLanguage(_customLocale); Localization.AddLanguageToPortals(_customLocale.LanguageId); } if (testFields.ContainsKey("Final Url")) { testFields["Final Url"] = testFields["Final Url"].Replace("{useAlias}", defaultAlias); } if (!(String.IsNullOrEmpty(language) && String.IsNullOrEmpty(skin))) { //add new primary alias _primaryAlias = new PortalAliasInfo { PortalID = PortalId, HTTPAlias = defaultAlias, CultureCode = language, Skin = skin, IsPrimary = true }; _primaryAlias.PortalAliasID = TestablePortalAliasController.Instance.AddPortalAlias(_primaryAlias); ExecuteTest(settings, testFields, true); } else { SetDefaultAlias(defaultAlias); ExecuteTest(settings, testFields, false); } }
public override void TestFixtureSetUp() { base.TestFixtureSetUp(); var tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); if (tab == null) { CreateTab(_aboutUsPageName); tab = TabController.Instance.GetTabByName(_aboutUsPageName, PortalId); } _tabId = tab.TabID; //Add Portal Aliases var aliasController = PortalAliasController.Instance; TestUtil.ReadStream(String.Format("{0}", "Aliases"), (line, header) => { string[] fields = line.Split(','); var alias = aliasController.GetPortalAlias(fields[0], PortalId); if (alias == null) { alias = new PortalAliasInfo { HTTPAlias = fields[0], PortalID = PortalId }; PortalAliasController.Instance.AddPortalAlias(alias); } }); TestUtil.ReadStream(String.Format("{0}", "Users"), (line, header) => { string[] fields = line.Split(','); TestUtil.AddUser(PortalId, fields[0].Trim(), fields[1].Trim(), fields[2].Trim()); }); }
public void UpdatePortalAliasInfo(PortalAliasInfo portalAlias) { Instance.UpdatePortalAlias(portalAlias); }
/// <summary> /// This method is used by the Url Master Url Rewriting process. The purpose of this method is to take the supplied array of Url parameters, and transform them into a module-specific querystring for the underlying re-written Url. /// </summary> /// <param name="urlParms">The array of parameters found after the DNN page path has been identified. No key/valeu pairs are identified, the parameters are converted from the /key/value/key2/value2 format into [key,value,key2,value2] format.</param> /// <param name="tabId">TabId of identified DNN page. </param> /// <param name="portalId">PortalId of identified DNN portal.</param> /// <param name="options">The current Friendly Url options being used by the module.</param> /// <param name="cultureCode">Identified language/culture code, if supplied.</param> /// <param name="portalAlias">Identified portalAlias object for the request.</param> /// <param name="messages">List of debug messages. Add to this list to help debug your module. Can be viewed in the reponse headers of the request, or in the 'Test Url Rewriting' section of the Url Master module.</param> /// <param name="status">Out parameter, returns the Http status of the request. May be 200,301,302, or 404. For normal rewriting, return a 200 value.</param> /// <param name="location">If a 301 or 302 is returned in the status parameter, then this must contain a valid redirect location. This should be a fully-qualified Url.</param> /// <returns>The querystring to be used for rewriting the Url. NOTE: doesn't need to include the tabid if the tabid parameter is > -1</returns> public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location) { string path = string.Join("/", urlParms); //initialise results and output variables location = null; //no redirect location if (messages == null) { messages = new List <string>(); } string result = ""; status = 200; //OK //prevent incorrect matches of Urls if (!Regex.IsMatch(path, @"(articleType/(?<type>[^/]+))|(ctl/[^/]+/(mid|moduleid)/\d)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { //store local options variable _options = options; //get the tab options TabUrlOptions urlOptions = GetTabUrlOptions(tabId); Hashtable queryStringIndex = null; int skipUpToIndex = -1; bool found = false; bool siteRootMatch = false; bool tabHasNAModule = false; //foreach (ModuleInfo mi in ModuleController.Instance.GetTabModules(tabId).Values) { //} if ((from ModuleInfo mi in ModuleController.Instance.GetTabModules(tabId).Values where mi.DesktopModule.FolderName.ToLower().Contains("dnnforge - newsarticles") select mi.ModuleTitle).Count() != 0) { tabHasNAModule = true; } //look for match on pattern for date and title - the pattern used by this provider //string path = string.Join("/", urlParms); //messages.Add("Checking for Items in Friendly Url path: " + path); if (urlParms.Length > 0) { //tabid == -1 when no dnn page path is in the Url. This means the Url Master module can't determine the DNN page based on the Url. //In this case, it is up to this provider to identify the correct tabId that matches the Url. Failure to do so will result in the incorrect tab being loaded when the page is rendered. if (tabId == -1) { siteRootMatch = true; if (_noDnnPagePathTabId > -1) { //tabid -1 means a 'site root' match - meaning that the dnn page path wasn't included in the Url tabId = _noDnnPagePathTabId;//if tabid = -1, it means a site root match (no dnn page path) so we substitute in the tabid where this is being used } } queryStringIndex = UrlController.GetQueryStringIndex(tabId, portalId, this, options, urlOptions, false); string pathBasedKey = string.Join("/", urlParms).ToLower(); string qs = null; if (queryStringIndex.ContainsKey(pathBasedKey)) { //that was easy- direct match qs = (string)queryStringIndex[pathBasedKey]; skipUpToIndex = urlParms.GetUpperBound(0); } else { //go through the parameter list backwards until we find a match for (int i = urlParms.GetUpperBound(0); i >= 0; i--) { //copy all the array minus the i index item int tempLength = i + 1; string[] tempParms = new string[tempLength]; Array.Copy(urlParms, 0, tempParms, 0, i + 1); //make a new key from the shorter array pathBasedKey = string.Join("/", tempParms).ToLower(); //check if that matches if (queryStringIndex.ContainsKey(pathBasedKey)) { qs = (string)queryStringIndex[pathBasedKey]; if (qs != null) { //the trimmed pieces need to be included skipUpToIndex = i; break; } } } } if (qs != null) { //found a querystring match found = true; messages.Add("Item Matched in Friendly Url Provider. Url : " + pathBasedKey + " Path : " + path); result += qs; } else { //no match, but look for a date archive pattern //903 : issue with matching other Urls that aren't archive Urls Regex archivePatternRegex = new Regex(@"(?<!year)(?<yr>(^|/)(?<yyyy>[\d]{4}))(?<mth>/(?<mm>[\d]{1,2}))?", RegexOptions.IgnoreCase); Match archivePatternMatch = archivePatternRegex.Match(path); if (archivePatternMatch.Success) { bool month = false, year = false; string mm = null, yyyy = null; //matched on date pattern, extract month/year Group mthGrp = archivePatternMatch.Groups["mth"]; if (mthGrp != null && mthGrp.Success) { mm = archivePatternMatch.Groups["mm"].Value; month = true; } Group yrGrp = archivePatternMatch.Groups["yyyy"]; if (yrGrp != null && yrGrp.Success) { //902 : don't allow invalid dates to be passed down int yearVal = 0; yyyy = yrGrp.Value; //check that year is a valid int, and that year is later than sql min date time if (int.TryParse(yyyy, out yearVal) && yearVal > 1753 && tabHasNAModule) { year = true; } } if (year) { qs = ""; if (this.NoDnnPagePathTabId == tabId) { qs += "?tabid=" + tabId.ToString(); } //add on the year qs += "&articleType=ArchiveView&year=" + yyyy; skipUpToIndex = 0;//1st position } if (year && month) { int mmVal = 0; if (int.TryParse(mm, out mmVal) && mmVal > 0 && mmVal < 13) { qs += "&month=" + mm; skipUpToIndex = 1;//2nd position } } if (year || month) { result += qs; } } } } if (skipUpToIndex >= 0) { //put on any remainder of the path that wasn't to do with the friendly Url //but only if there was *something* in the friendly url that we interpreted string remainder = base.CreateQueryStringFromParameters(urlParms, skipUpToIndex); //put it all together for the final rewrite string result += remainder; } } return(result); }
/// ----------------------------------------------------------------------------- /// <summary> /// AddAlias runs when the Add button is clicked /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 12/12/2008 Created /// </history> /// ----------------------------------------------------------------------------- private void AddAlias(object sender, EventArgs e) { //Add a new empty rule and set the editrow to the new row var portalAlias = new PortalAliasInfo(); portalAlias.PortalID = intPortalId; Aliases.Add(portalAlias); dgPortalAlias.EditItemIndex = Aliases.Count - 1; //Set the AddMode to true AddMode = true; //Rebind the collection BindAliases(); }
/// <summary> /// Gets the host portal settings. /// </summary> /// <returns>Host portal settings</returns> public static PortalSettings GetHostPortalSettings() { int TabId = -1; int PortalId = -1; PortalAliasInfo objPortalAliasInfo = null; //if the portal alias exists if (Host.HostPortalID > Null.NullInteger) { PortalId = Host.HostPortalID; // use the host portal objPortalAliasInfo = new PortalAliasInfo(); objPortalAliasInfo.PortalID = PortalId; } // load the PortalSettings into current context return new PortalSettings(TabId, objPortalAliasInfo); }
public void UpdatePortalAlias(PortalAliasInfo portalAlias) => ((IPortalAliasService)this).UpdatePortalAlias(portalAlias);
public void AdvancedUrlRewriter_PrimaryPortalAlias(Dictionary<string, string> testFields) { string defaultAlias = testFields["DefaultAlias"]; var settings = UrlTestFactoryClass.GetSettings("UrlRewrite", testFields["TestName"]); settings.PortalId = PortalId; string language = testFields["Language"].Trim(); string skin = testFields["Skin"].Trim(); if (!String.IsNullOrEmpty(language)) { _customLocale = new Locale { Code = language, Fallback = "en-US" }; _customLocale.Text = CultureInfo.GetCultureInfo(_customLocale.Code).NativeName; Localization.SaveLanguage(_customLocale); Localization.AddLanguageToPortals(_customLocale.LanguageId); } if (testFields.ContainsKey("Final Url")) { testFields["Final Url"] = testFields["Final Url"].Replace("{useAlias}", defaultAlias); } PortalController.UpdatePortalSetting(PortalId, "PortalAliasMapping", "REDIRECT", "en-us"); var alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, PortalId); if (alias == null) { alias = new PortalAliasInfo { HTTPAlias = defaultAlias, PortalID = PortalId, IsPrimary = true }; if (!(String.IsNullOrEmpty(language) && String.IsNullOrEmpty(skin))) { alias.CultureCode = language; alias.Skin = skin; } PortalAliasController.Instance.AddPortalAlias(alias); } SetDefaultAlias(defaultAlias); ExecuteTest(settings, testFields, false); alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, PortalId); if (alias != null) { PortalAliasController.Instance.DeletePortalAlias(alias); } }
public override string TransformFriendlyUrlToQueryString(string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, string cultureCode, DotNetNuke.Entities.Portals.PortalAliasInfo portalAlias, ref List <string> messages, out int status, out string location) { status = 200; location = null; string result = string.Empty, Slug = string.Empty, PageName = string.Empty; PortalSettings pS = null; bool PageNameRedirect = false; urlParms = urlParms.Select(s => s.ToLower()).Distinct().ToArray(); List <string> urlParmsList = new List <string>(urlParms).ConvertAll(u => u.ToLower()); int SlugTabID = URLManager.GetSlugTabID(urlParms, ref Slug, tabId, PortalController.Instance.GetPortal(portalId)); if (SlugTabID != -1) //Slug Found { URLEntity CurrentURL = URLManager.GetURL(Slug); //Redirect if it's not the default URL if (CurrentURL != null && !CurrentURL.IsDefault) { InitPortalSettings(ref pS, tabId, portalAlias); return(Redirect(out status, out location, portalId, pS, SlugTabID, result, CurrentURL, null)); } if (pS == null) { pS = new PortalSettings(tabId, portalAlias); } //DNN 8580 //https://dnntracker.atlassian.net/browse/DNN-8580?page=com.googlecode.jira-suite-utilities%3Atransitions-summary-tabpanel ClearUrlParams(ref urlParmsList, ref PageName, Slug, SlugTabID, pS); //Tab not identified...need redirect if (tabId == -1) { InitPortalSettings(ref pS, tabId, portalAlias); if (CurrentURL.IgnorePageName) { return(string.Empty); } else { //Redirect based on Include PageName if we're not on homepage if (SlugTabID != pS.HomeTabId && CurrentURL.PageName && !urlParmsList.Contains(PageName) && !string.Join("/", urlParmsList).Contains(PageName)) { PageNameRedirect = true; } else if (!CurrentURL.PageName && (urlParmsList.Contains(PageName) || string.Join("/", urlParmsList).Contains(PageName))) { PageNameRedirect = true; } //Remove PageName foreach (var item in PageName.Split('/')) { urlParmsList.Remove(item); } //Setup Rewrite Path result = "?TabId=" + SlugTabID.ToString(); } } string remainder = base.CreateQueryStringFromParameters(urlParmsList.ToArray(), -1); string Prefix = urlParmsList.Count % 2 == 0 ? string.Empty : "="; if (PageNameRedirect) { InitPortalSettings(ref pS, tabId, portalAlias); return(Redirect(out status, out location, portalId, pS, SlugTabID, result, CurrentURL, remainder)); } //Rewrite URL to appropriate page if (result.StartsWith("?TabId=") && !string.IsNullOrEmpty(Slug)) { result += "&" + Slug + remainder; } else { result += Slug + remainder; } } return(result); }
public void OnBeginRequest(object s, EventArgs e) { _forumId = -1; _tabId = -1; _moduleId = -1; _topicId = -1; _page = 1; _contentId = -1; _archived = 0; _forumgroupId = -1; _mainSettings = null; _categoryId = -1; _tagId = -1; HttpApplication app = (HttpApplication)s; HttpServerUtility Server = app.Server; HttpRequest Request = app.Request; HttpResponse Response = app.Response; string requestedPath = app.Request.Url.AbsoluteUri; HttpContext Context = ((HttpApplication)s).Context; int PortalId = -1; DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null; string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); objPortalAliasInfo = PortalAliasController.Instance.GetPortalAlias(HttpContext.Current.Request.Url.Host); if (Request.RawUrl.ToLowerInvariant().Contains("404.aspx")) { string sEx = ".jpg,.gif,.png,.swf,.js,.css,.html,.htm,desktopmodules,portals,.ashx,.ico,.txt,.doc,.docx,.pdf,.xml,.xls,.xlsx,.ppt,.pptx,.csv,.zip,.asmx,.aspx"; foreach (string sn in sEx.Split(',')) { if (sUrl.Contains(sn)) { // IO.File.AppendAllText(sPath, Request.RawUrl & "165<br />") return; } } } if (Request.Url.LocalPath.ToLower().Contains("scriptresource.axd") || Request.Url.LocalPath.ToLower().Contains("webresource.axd") || Request.Url.LocalPath.ToLower().Contains("viewer.aspx") || Request.Url.LocalPath.ToLower().Contains("cb.aspx") || Request.Url.LocalPath.ToLower().Contains("filesupload.aspx") || Request.Url.LocalPath.ToLower().Contains(".gif") || Request.Url.LocalPath.ToLower().Contains(".jpg") || Request.Url.LocalPath.ToLower().Contains(".css") || Request.Url.LocalPath.ToLower().Contains(".png") || Request.Url.LocalPath.ToLower().Contains(".swf") || Request.Url.LocalPath.ToLower().Contains(".htm") || Request.Url.LocalPath.ToLower().Contains(".html") || Request.Url.LocalPath.ToLower().Contains(".ashx") || Request.Url.LocalPath.ToLower().Contains(".cur") || Request.Url.LocalPath.ToLower().Contains(".ico") || Request.Url.LocalPath.ToLower().Contains(".txt") || Request.Url.LocalPath.ToLower().Contains(".pdf") || Request.Url.LocalPath.ToLower().Contains(".xml") || Request.Url.LocalPath.ToLower().Contains("/portals/") || Request.Url.LocalPath.ToLower().Contains("/desktopmodules/") || Request.Url.LocalPath.ToLower().Contains("evexport.aspx") || Request.Url.LocalPath.ToLower().Contains("signupjs.aspx") || Request.Url.LocalPath.ToLower().Contains("evsexport.aspx") || Request.Url.LocalPath.ToLower().Contains("fbcomm.aspx") || Request.Url.LocalPath.ToLower().Contains(".aspx") || Request.Url.LocalPath.ToLower().Contains(".js")) { return; } if (Request.Url.LocalPath.ToLower().Contains("install.aspx") || Request.Url.LocalPath.ToLower().Contains("installwizard.aspx") || Request.Url.LocalPath.ToLower().Contains("captcha.aspx") || Request.RawUrl.Contains("viewer.aspx") || Request.RawUrl.Contains("blank.html") || Request.RawUrl.Contains("default.htm") || Request.RawUrl.Contains("autosuggest.aspx")) { return; } PortalId = objPortalAliasInfo.PortalID; string searchURL = sUrl; searchURL = searchURL.Replace(objPortalAliasInfo.HTTPAlias, string.Empty); if (searchURL.Length < 2) { return; } string query = string.Empty; if (searchURL.Contains("?")) { query = searchURL.Substring(searchURL.IndexOf("?")); searchURL = searchURL.Substring(0, searchURL.IndexOf("?") - 1); } string newSearchURL = string.Empty; foreach (string up in searchURL.Split('/')) { if (!(string.IsNullOrEmpty(up))) { if (!(SimulateIsNumeric.IsNumeric(up))) { newSearchURL += up + "/"; } } } bool canContinue = false; Data.Common db = new Data.Common(); string tagName = string.Empty; string catName = string.Empty; if (newSearchURL.Contains("/category/") || newSearchURL.Contains("/tag/")) { if (newSearchURL.Contains("/category/")) { string cat = "/category/"; int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(cat) + cat.Length + 1); string catString = newSearchURL.Substring(newSearchURL.IndexOf(cat), iEnd - newSearchURL.IndexOf(cat)); catName = catString.Replace(cat, string.Empty); catName = catName.Replace("/", string.Empty); newSearchURL = newSearchURL.Replace(catString, string.Empty); } if (newSearchURL.Contains("/tag/")) { string tag = "/tag/"; int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(tag) + tag.Length + 1); string tagString = newSearchURL.Substring(newSearchURL.IndexOf(tag), iEnd - newSearchURL.IndexOf(tag)); tagName = tagString.Replace(tag, string.Empty); tagName = tagName.Replace("/", string.Empty); newSearchURL = newSearchURL.Replace(tagString, string.Empty); } } if ((sUrl.Contains("afv") && sUrl.Contains("post")) | (sUrl.Contains("afv") && sUrl.Contains("confirmaction")) | (sUrl.Contains("afv") && sUrl.Contains("sendto")) | (sUrl.Contains("afv") && sUrl.Contains("modreport")) | (sUrl.Contains("afv") && sUrl.Contains("search")) | sUrl.Contains("dnnprintmode") || sUrl.Contains("asg") || (sUrl.Contains("afv") && sUrl.Contains("modtopics"))) { return; } try { using (IDataReader dr = db.URLSearch(PortalId, newSearchURL)) { while (dr.Read()) { _tabId = int.Parse(dr["TabID"].ToString()); _moduleId = int.Parse(dr["ModuleId"].ToString()); _forumgroupId = int.Parse(dr["ForumGroupId"].ToString()); _forumId = int.Parse(dr["ForumId"].ToString()); _topicId = int.Parse(dr["TopicId"].ToString()); _archived = int.Parse(dr["Archived"].ToString()); _otherId = int.Parse(dr["OtherId"].ToString()); _urlType = int.Parse(dr["UrlType"].ToString()); canContinue = true; } dr.Close(); } } catch (Exception ex) { } if (!(string.IsNullOrEmpty(catName))) { _categoryId = db.Tag_GetIdByName(PortalId, _moduleId, catName, true); _otherId = _categoryId; _urlType = 2; } if (!(string.IsNullOrEmpty(tagName))) { _tagId = db.Tag_GetIdByName(PortalId, _moduleId, tagName, false); _otherId = _tagId; _urlType = 3; } if (_archived == 1) { sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1); if (!(string.IsNullOrEmpty(sUrl))) { string sHost = objPortalAliasInfo.HTTPAlias; if (sUrl.StartsWith("/")) { sUrl = sUrl.Substring(1); } if (!(sHost.EndsWith("/"))) { sHost += "/"; } sUrl = sHost + sUrl; if (!(sUrl.EndsWith("/"))) { sUrl += "/"; } if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } if (_moduleId > 0) { Entities.Modules.ModuleController objModules = new Entities.Modules.ModuleController(); SettingsInfo objSettings = new SettingsInfo(); objSettings.MainSettings = objModules.GetModuleSettings(_moduleId); _mainSettings = objSettings; // DataCache.MainSettings(_moduleId) } if (_mainSettings == null) { return; } if (!_mainSettings.URLRewriteEnabled) { return; } if (!canContinue && (Request.RawUrl.Contains(ParamKeys.TopicId) || Request.RawUrl.Contains(ParamKeys.ForumId) || Request.RawUrl.Contains(ParamKeys.GroupId))) { sUrl = HandleOldUrls(Request.RawUrl, objPortalAliasInfo.HTTPAlias); if (!(string.IsNullOrEmpty(sUrl))) { if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } if (!canContinue) { string topicUrl = string.Empty; if (newSearchURL.EndsWith("/")) { newSearchURL = newSearchURL.Substring(0, newSearchURL.Length - 1); } if (newSearchURL.Contains("/")) { topicUrl = newSearchURL.Substring(newSearchURL.LastIndexOf("/")); } topicUrl = topicUrl.Replace("/", string.Empty); if (!(string.IsNullOrEmpty(topicUrl))) { Data.Topics topicsDb = new Data.Topics(); _topicId = topicsDb.TopicIdByUrl(PortalId, _moduleId, topicUrl.ToLowerInvariant()); if (_topicId > 0) { sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1); } else { sUrl = string.Empty; } if (!(string.IsNullOrEmpty(sUrl))) { string sHost = objPortalAliasInfo.HTTPAlias; if (sHost.EndsWith("/") && sUrl.StartsWith("/")) { sUrl = sHost.Substring(0, sHost.Length - 1) + sUrl; } else if (!(sHost.EndsWith("/")) && !(sUrl.StartsWith("/"))) { sUrl = sHost + "/" + sUrl; } else { sUrl = sHost + sUrl; } if (sUrl.StartsWith("/")) { sUrl = sUrl.Substring(1); } if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } if (!(string.IsNullOrEmpty(sUrl))) { Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } } } if (canContinue) { if (searchURL != newSearchURL) { string urlTail = searchURL.Replace(newSearchURL, string.Empty); if (urlTail.StartsWith("/")) { urlTail = urlTail.Substring(1); } if (urlTail.EndsWith("/")) { urlTail = urlTail.Substring(0, urlTail.Length - 1); } if (urlTail.Contains("/")) { urlTail = urlTail.Substring(0, urlTail.IndexOf("/") - 1); } if (SimulateIsNumeric.IsNumeric(urlTail)) { _page = Convert.ToInt32(urlTail); } } string sPage = string.Empty; sPage = "&afpg=" + _page.ToString(); string qs = string.Empty; if (sUrl.Contains("?")) { qs = "&" + sUrl.Substring(sUrl.IndexOf("?") + 1); } string catQS = string.Empty; if (_categoryId > 0) { catQS = "&act=" + _categoryId.ToString(); } string sendTo = string.Empty; if (_topicId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aft=" + _topicId + sPage + qs); } else if (_forumId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&aff=" + _forumId + sPage + qs + catQS); } else if (_forumgroupId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afg=" + _forumgroupId + sPage + qs + catQS); } else if (_urlType == 2 && _otherId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&act=" + _otherId + sPage + qs); } else if (_urlType == 3 && _otherId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=tags&aftg=" + _otherId + sPage + qs); } else if (_urlType == 1) { string v = string.Empty; switch (_otherId) { case 1: v = "unanswered"; break; case 2: v = "notread"; break; case 3: v = "mytopics"; break; case 4: v = "activetopics"; break; case 5: v = "afprofile"; break; } sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=" + v + sPage + qs); } else if (_tabId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + sPage + qs); } RewriteUrl(app.Context, sendTo); } }
private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) { //handle Auto-Add Alias if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) { //Need to determine if this is a real 404 or a possible new alias. var portalId = Host.Host.HostPortalID; if (portalId > Null.NullInteger) { if (string.IsNullOrEmpty(result.DomainName)) { result.DomainName = Globals.GetDomainName(context.Request); //parse the domain name out of the request } //Get all the existing aliases var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); bool autoaddAlias; bool isPrimary = false; if (!aliases.Any()) { autoaddAlias = true; isPrimary = true; } else { autoaddAlias = true; foreach (var alias in aliases) { if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 && result.DomainName.Length >= alias.HTTPAlias.Length) { autoaddAlias = false; break; } } } if (autoaddAlias) { var portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = result.DomainName, IsPrimary = isPrimary }; PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); context.Response.Redirect(context.Request.Url.ToString(), true); } } } if (context != null) { HttpRequest request = context.Request; HttpResponse response = context.Response; HttpServerUtility server = context.Server; const string errorPageHtmlHeader = @"<html><head><title>{0}</title></head><body>"; const string errorPageHtmlFooter = @"</body></html>"; var errorPageHtml = new StringWriter(); CustomErrorsSection ceSection = null; //876 : security catch for custom error reading try { ceSection = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors"); } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { //on some medium trust environments, this will throw an exception for trying to read the custom Errors //do nothing } /* 454 new 404/500 error handling routine */ bool useDNNTab = false; int errTabId = -1; string errUrl = null; string status = ""; bool isPostback = false; if (settings != null) { if (request.RequestType == "POST") { isPostback = true; } if (result != null && ex != null) { result.DebugMessages.Add("Exception: " + ex.Message); result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); if (ex.InnerException != null) { result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); } else { result.DebugMessages.Add("Inner Ex : null"); } } string errRH; string errRV; int statusCode; if (result != null && result.Action != ActionType.Output404) { //output everything but 404 (usually 500) if (settings.TabId500 > -1) //tabid specified for 500 error page, use that { useDNNTab = true; errTabId = settings.TabId500; } errUrl = settings.Url500; errRH = "X-UrlRewriter-500"; errRV = "500 Rewritten to {0} : {1}"; statusCode = 500; status = "500 Internal Server Error"; } else //output 404 error { if (settings.TabId404 > -1) //if the tabid is specified for a 404 page, then use that { useDNNTab = true; errTabId = settings.TabId404; } if (!String.IsNullOrEmpty(settings.Regex404)) //with 404 errors, there's an option to catch certain urls and use an external url for extra processing. { try { //944 : check the original Url in case the requested Url has been rewritten before discovering it's a 404 error string requestedUrl = request.Url.ToString(); if (result != null && string.IsNullOrEmpty(result.OriginalPath) == false) { requestedUrl = result.OriginalPath; } if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { useDNNTab = false; //if we have a match in the 404 regex value, then don't use the tabid } } catch (Exception regexEx) { //.some type of exception : output in response header, and go back to using the tabid response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); } } errUrl = settings.Url404; errRH = "X-UrlRewriter-404"; errRV = "404 Rewritten to {0} : {1} : Reason {2}"; status = "404 Not Found"; statusCode = 404; } // check for 404 logging if ((result == null || result.Action == ActionType.Output404)) { //Log 404 errors to Event Log UrlRewriterUtils.Log404(request, settings, result); } //912 : use unhandled 404 switch string reason404 = null; bool unhandled404 = true; if (useDNNTab && errTabId > -1) { unhandled404 = false; //we're handling it here TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); if (errTab != null) { bool redirect = false; //ok, valid tabid. what we're going to do is to load up this tab via a rewrite of the url, and then change the output status string reason = "Not Found"; if (result != null) { reason = result.Reason.ToString(); } response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", reason)); //show debug messages even if in debug mode if (context != null && response != null && result != null && showDebug) { ShowDebugData(context, result.OriginalPath, result, null); } if (!isPostback) { response.ClearContent(); response.StatusCode = statusCode; response.Status = status; } else { redirect = true; //redirect postbacks as you can't postback successfully to a server.transfer } errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, ""); //have to update the portal settings with the new tabid PortalSettings ps = null; if (context != null && context.Items != null) { if (context.Items.Contains("PortalSettings")) { ps = (PortalSettings) context.Items["PortalSettings"]; context.Items.Remove("PortalSettings"); //nix it from the context } } if (ps != null && ps.PortalAlias != null) { ps = new PortalSettings(errTabId, ps.PortalAlias); } else { if (result.HttpAlias != null && result.PortalId > -1) { PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); ps = new PortalSettings(errTabId, pa); } else { //912 : handle 404 when no valid portal can be identified //results when iis is configured to handle portal alias, but //DNN isn't. This always returns 404 because a multi-portal site //can't just show the 404 page of the host site. ArrayList portals = PortalController.Instance.GetPortals(); if (portals != null && portals.Count == 1) { //single portal install, load up portal settings for this portal var singlePortal = (PortalInfo) portals[0]; //list of aliases from database var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); //list of aliases from Advanced Url settings List<string> chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); PortalAliasInfo useFor404 = null; //go through all aliases and either get the first valid one, or the first //as chosen in the advanced url management settings foreach (var pa in aliases) { if (useFor404 == null) { useFor404 = pa; //first one by default } //matching? if (chosen != null && chosen.Count > 0) { if (chosen.Contains(pa.HTTPAlias)) { useFor404 = pa; } } else { break; //no further checking } } //now configure that as the portal settings if (useFor404 != null) { //create portal settings context for identified portal alias in single portal install ps = new PortalSettings(errTabId, useFor404); } } else { reason404 = "Requested domain name is not configured as valid website"; unhandled404 = true; } } } if (ps != null) { //re-add the context items portal settings back in context.Items.Add("PortalSettings", ps); } if (redirect) { errUrl = TestableGlobals.Instance.NavigateURL(); response.Redirect(errUrl, true); //redirect and end response. //It will mean the user will have to postback again, but it will work the second time } else { if (transfer) { //execute a server transfer to the default.aspx?tabid=xx url //767 : object not set error on extensionless 404 errors if (context.User == null) { context.User = Thread.CurrentPrincipal; } response.TrySkipIisCustomErrors = true; //881 : spoof the basePage object so that the client dependency framework //is satisfied it's working with a page-based handler IHttpHandler spoofPage = new CDefault(); context.Handler = spoofPage; server.Transfer("~/" + errUrl, true); } else { context.RewritePath("~/Default.aspx", false); response.TrySkipIisCustomErrors = true; response.Status = "404 Not Found"; response.StatusCode = 404; } } } } //912 : change to new if statement to handle cases where the TabId404 couldn't be handled correctly if (unhandled404) { //proces the error on the external Url by rewriting to the external url if (!String.IsNullOrEmpty(errUrl)) { response.ClearContent(); response.TrySkipIisCustomErrors = true; string reason = "Not Found"; if (result != null) { reason = result.Reason.ToString(); } response.AppendHeader(errRH, string.Format(errRV, "Url", errUrl, reason)); if (reason404 != null) { response.AppendHeader("X-Url-Master-404-Data", reason404); } response.StatusCode = statusCode; response.Status = status; server.Transfer("~/" + errUrl, true); } else { errorPageHtml.Write(status + "<br>The requested Url does not return any valid content."); if (reason404 != null) { errorPageHtml.Write(status + "<br>" + reason404); } errorPageHtml.Write("<div style='font-weight:bolder'>Administrators</div>"); errorPageHtml.Write("<div>Change this message by configuring a specific 404 Error Page or Url for this website.</div>"); //output a reason for the 404 string reason = ""; if (result != null) { reason = result.Reason.ToString(); } if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) { response.AppendHeader(errRH, reason); } response.StatusCode = statusCode; response.Status = status; } } } else { //fallback output if not valid settings if (result != null && result.Action == ActionType.Output404) { //don't restate the requested Url to prevent cross site scripting errorPageHtml.Write("404 Not Found<br>The requested Url does not return any valid content."); response.StatusCode = 404; response.Status = "404 Not Found"; } else { //error, especially if invalid result object errorPageHtml.Write("500 Server Error<br><div style='font-weight:bolder'>An error occured during processing : if possible, check the event log of the server</div>"); response.StatusCode = 500; response.Status = "500 Internal Server Error"; if (result != null) { result.Action = ActionType.Output500; } } } if (ex != null) { if (context != null) { if (context.Items.Contains("UrlRewrite:Exception") == false) { context.Items.Add("UrlRewrite:Exception", ex.Message); context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); } } if (ceSection != null && ceSection.Mode == CustomErrorsMode.Off) { errorPageHtml.Write(errorPageHtmlHeader); errorPageHtml.Write("<div style='font-weight:bolder'>Exception:</div><div>" + ex.Message + "</div>"); errorPageHtml.Write("<div style='font-weight:bolder'>Stack Trace:</div><div>" + ex.StackTrace + "</div>"); errorPageHtml.Write("<div style='font-weight:bolder'>Administrators</div>"); errorPageHtml.Write("<div>You can see this exception because the customErrors attribute in the web.config is set to 'off'. Change this value to 'on' or 'RemoteOnly' to show Error Handling</div>"); try { if (errUrl != null && errUrl.StartsWith("~")) { errUrl = VirtualPathUtility.ToAbsolute(errUrl); } } finally { if (errUrl != null) { errorPageHtml.Write("<div>The error handling would have shown this page : <a href='" + errUrl + "'>" + errUrl + "</a></div>"); } else { errorPageHtml.Write("<div>The error handling could not determine the correct page to show.</div>"); } } } } string errorPageHtmlBody = errorPageHtml.ToString(); if (errorPageHtmlBody.Length > 0) { response.Write(errorPageHtmlHeader); response.Write(errorPageHtmlBody); response.Write(errorPageHtmlFooter); } if (ex != null) { UrlRewriterUtils.LogExceptionInRequest(ex, status, result); } } }
private PortalAliasInfo GetPortalAliasInternal(string httpAlias) { string strPortalAlias; //try the specified alias first PortalAliasInfo portalAlias = GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); //domain.com and www.domain.com should be synonymous if (portalAlias == null) { if (httpAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) { //try alias without the "www." prefix strPortalAlias = httpAlias.Replace("www.", ""); } else //try the alias with the "www." prefix { strPortalAlias = string.Concat("www.", httpAlias); } //perform the lookup portalAlias = GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); } //allow domain wildcards if (portalAlias == null) { //remove the domain prefix ( ie. anything.domain.com = domain.com ) if (httpAlias.IndexOf(".", StringComparison.Ordinal) != -1) { strPortalAlias = httpAlias.Substring(httpAlias.IndexOf(".", StringComparison.Ordinal) + 1); } else //be sure we have a clean string (without leftovers from preceding 'if' block) { strPortalAlias = httpAlias; } //try an explicit lookup using the wildcard entry ( ie. *.domain.com ) portalAlias = GetPortalAliasLookupInternal("*." + strPortalAlias.ToLowerInvariant()) ?? GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); if (portalAlias == null) { //try a lookup using "www." + raw domain portalAlias = GetPortalAliasLookupInternal("www." + strPortalAlias.ToLowerInvariant()); } } if (portalAlias == null) { //check if this is a fresh install ( no alias values in collection ) var controller = new PortalAliasController(); var portalAliases = controller.GetPortalAliasesInternal(); if (portalAliases.Keys.Count == 0 || (portalAliases.Count == 1 && portalAliases.ContainsKey("_default"))) { //relate the PortalAlias to the default portal on a fresh database installation DataProvider.Instance().UpdatePortalAlias(httpAlias.ToLowerInvariant().Trim('/'), UserController.Instance.GetCurrentUserInfo().UserID); EventLogController.Instance.AddLog("PortalAlias", httpAlias, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALALIAS_UPDATED); //clear the cachekey "GetPortalByAlias" otherwise portalalias "_default" stays in cache after first install DataCache.RemoveCache("GetPortalByAlias"); //try again portalAlias = GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); } } return(portalAlias); }