public void TryAdd()
        {
            const string KEY   = "key";
            const string VALUE = "value";

            var sharedDictionary = new SharedDictionary <string, string>(LockingStrategy);

            bool doInsert = false;

            using (ISharedCollectionLock l = sharedDictionary.GetReadLock())
            {
                if (!sharedDictionary.ContainsKey(KEY))
                {
                    doInsert = true;
                }
            }

            if (doInsert)
            {
                using (ISharedCollectionLock l = sharedDictionary.GetWriteLock())
                {
                    if (!sharedDictionary.ContainsKey(KEY))
                    {
                        sharedDictionary.Add(KEY, VALUE);
                    }
                }
            }

            CollectionAssert.AreEqual(new Dictionary <string, string> {
                { KEY, VALUE }
            }, sharedDictionary.BackingDictionary);
        }
示例#2
0
        /// <summary>
        /// [jmarino]  2011-06-16 Check for ContainsKey for a write added.
        /// </summary>
        /// <param name="portalId"></param>
        /// <returns></returns>
        private static string GetCacheFolder(int portalId)
        {
            string cacheFolder;

            using (var readerLock = CacheFolderPath.GetReadLock())
            {
                if (CacheFolderPath.TryGetValue(portalId, out cacheFolder))
                {
                    return(cacheFolder);
                }
            }

            var portalInfo = PortalController.Instance.GetPortal(portalId);

            string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath;

            if (!string.IsNullOrEmpty(homeDirectoryMapPath))
            {
                cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\");
                if (!Directory.Exists(cacheFolder))
                {
                    Directory.CreateDirectory(cacheFolder);
                }
            }

            using (var writerLock = CacheFolderPath.GetWriteLock())
            {
                if (!CacheFolderPath.ContainsKey(portalId))
                {
                    CacheFolderPath.Add(portalId, cacheFolder);
                }
            }

            return(cacheFolder);
        }
        public void DisposedWriteLockDeniesRead()
        {
            var d = new SharedDictionary <string, string>(LockingStrategy);

            ISharedCollectionLock l = d.GetWriteLock();

            l.Dispose();

            d.ContainsKey("foo");
        }
        private static bool ResourceFileMayExist(SharedDictionary <string, bool> resourceFileExistsLookup, string cacheKey)
        {
            bool mayExist;

            using (resourceFileExistsLookup.GetReadLock())
            {
                mayExist = !resourceFileExistsLookup.ContainsKey(cacheKey) || resourceFileExistsLookup[cacheKey];
            }
            return(mayExist);
        }
示例#5
0
        public void DisposedWriteLockDeniesRead()
        {
            var d = new SharedDictionary <string, string>(this.LockingStrategy);

            ISharedCollectionLock l = d.GetWriteLock();

            l.Dispose();

            Assert.Throws <ReadLockRequiredException>(() => d.ContainsKey("foo"));
        }
示例#6
0
        private static void CheckIconOnDisk(string path)
        {
            using (_iconsStatusOnDisk.GetReadLock())
            {
                if (_iconsStatusOnDisk.ContainsKey(path))
                {
                    return;
                }
            }

            using (_iconsStatusOnDisk.GetWriteLock())
            {
                if (!_iconsStatusOnDisk.ContainsKey(path))
                {
                    _iconsStatusOnDisk.Add(path, true);
                    string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, path.Replace('/', '\\'));
                    if (!File.Exists(iconPhysicalPath))
                    {
                        Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath));
                    }
                }
            }
        }
示例#7
0
        private static object GetCachedDataFromDictionary(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired)
        {
            object cachedObject = null;

            bool isFound;

            using (ISharedCollectionLock readLock = dictionaryCache.GetReadLock())
            {
                isFound = dictionaryCache.TryGetValue(cacheItemArgs.CacheKey, out cachedObject);
            }

            if (!isFound)
            {
                // get object from data source using delegate
                try
                {
                    if (cacheItemExpired != null)
                    {
                        cachedObject = cacheItemExpired(cacheItemArgs);
                    }
                    else
                    {
                        cachedObject = null;
                    }
                }
                catch (Exception ex)
                {
                    cachedObject = null;
                    Exceptions.LogException(ex);
                }

                using (ISharedCollectionLock writeLock = dictionaryCache.GetWriteLock())
                {
                    if (!dictionaryCache.ContainsKey(cacheItemArgs.CacheKey))
                    {
                        if (cachedObject != null)
                        {
                            dictionaryCache[cacheItemArgs.CacheKey] = cachedObject;
                        }
                    }
                }
            }

            return(cachedObject);
        }
示例#8
0
        private static void AddEntryToDictionary(SharedDictionary <int, SharedDictionary <string, string> > existingTabs, int portalId, TabInfo tab, string cultureKey, string url)
        {
            int tabid = tab.TabID;

            using (existingTabs.GetWriteLock())
            {
                if (existingTabs.ContainsKey(tabid) == false)
                {
                    var entry = new SharedDictionary <string, string>();
                    using (entry.GetWriteLock())
                    {
                        entry.Add(cultureKey, url);
                    }

                    // 871 : use lower case culture code as key
                    existingTabs.Add(tab.TabID, entry);
                }
                else
                {
                    SharedDictionary <string, string> entry = existingTabs[tabid];

                    // replace tab if existing but was retreieved from tabs call
                    if (tab.PortalID == portalId || portalId == -1)
                    {
                        using (entry.GetWriteLock())
                        {
                            if (entry.ContainsKey(cultureKey) == false)
                            {
                                // add the culture and set in parent dictionary
                                // 871 : use lower case culture code as key
                                entry.Add(cultureKey, url);
                                existingTabs[tabid] = entry;
                            }
                        }
                    }
                }
            }
        }
 private static bool ResourceFileMayExist(SharedDictionary<string, bool> resourceFileExistsLookup, string cacheKey)
 {
     bool mayExist;
     using (resourceFileExistsLookup.GetReadLock())
     {
         mayExist = !resourceFileExistsLookup.ContainsKey(cacheKey) || resourceFileExistsLookup[cacheKey];
     }
     return mayExist;
 }
        private static SharedDictionary<string, string> BuildTabDictionary(out PathSizes pathSizes,
                                                                                FriendlyUrlSettings settings,
                                                                                int buildPortalId,
                                                                                SharedDictionary<string, string> tabIndex,
                                                                                out Hashtable homePageSkins,
                                                                                out SharedDictionary<string, string> portalTabPathDictionary,
                                                                                Guid parentTraceId)
        {
            if (tabIndex == null)
            {
                tabIndex = new SharedDictionary<string, string>();
            }

            homePageSkins = new Hashtable();
            pathSizes = new PathSizes { MinAliasDepth = 10, MinTabPathDepth = 10, MaxAliasDepth = 0, MaxTabPathDepth = 0 };

            portalTabPathDictionary = null;
            if (buildPortalId >= 0)
            {
                //dictioanry for storing the tab paths in
                portalTabPathDictionary = new SharedDictionary<string, string>();

                //init the duplicate key check dictionary - disposed after the tab dictionary is built
                var dupCheck = new Dictionary<string, DupKeyCheck>();

                //get the list of tabs for all portals
                //new for 2.0 : only get tabs by portal
                //770 : keep track of custom alias tabs
                Dictionary<int, TabInfo> tabs = FriendlyUrlController.GetTabs(buildPortalId, false, settings);

                const bool hasSiteRootRedirect = true;

                /* for the requested build portal, add in the standard urls and special rules */
                //735 : switch to custom method for getting portal
                PortalInfo thisPortal = CacheController.GetPortal(buildPortalId, true);
                List<PortalAliasInfo> chosenAliases;
                Dictionary<string, string> chosenAliasesCultures;
                var aliasSpecificCultures = new List<string>();
                var usingHttpAliases = new List<string>();
                var customHttpAliasesUsed = new List<string>();
                GetAliasFromSettings(buildPortalId, out chosenAliases, out chosenAliasesCultures);
                FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings);

                //keep a list of cultures specific to an alias
                foreach (string culture in chosenAliasesCultures.Values.Where(culture => aliasSpecificCultures.Contains(culture) == false))
                {
                    aliasSpecificCultures.Add(culture);
                }

                //the home tabid of the portal - should be the home page for the default language (all others will get page path)
                int homeTabId = thisPortal.HomeTabId;

                //Add site root redirects
                AddSiteRootRedirects(pathSizes, tabIndex, chosenAliases, hasSiteRootRedirect, dupCheck, usingHttpAliases);

                //add in any internal aliases as valid aliase
                AddInternalAliases(settings, usingHttpAliases);

                //loop through each tab and add all of the various Url paths that the tab can be found with, 
                //for all aliases the tab will be used with
                foreach (TabInfo tab in tabs.Values)
                {
                    int tabPathDepth = 0;

                    //935 : get the tab path and add to the tab path dictionary if it's not just a straight conversion of the TabPath value
                    //bool modified;
                    string tabPath = TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId);
                    string tabKey = tab.TabID.ToString();

                    using (portalTabPathDictionary.GetWriteLock())
                    {
                        if (portalTabPathDictionary.ContainsKey(tabKey) == false)
                        {
                            portalTabPathDictionary.Add(tabKey, tabPath);
                        }
                    }

                    //now, go through the list of tabs for this portal and build up the dictionary
                    if ((settings.FriendlyAdminHostUrls && tab.PortalID == -1) || tab.PortalID == buildPortalId)
                    {
                        //check if this value has been excluded from being a friendly url
                        bool isExcluded = RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true);
                        string tabCulture = tab.CultureCode;

                        //770 : custom alias per tab (and culture)
                        bool customAliasUsed;
                        var customHttpAlias = ManageCustomAliases(tabCulture,
                                                                    thisPortal,
                                                                    tab,
                                                                    usingHttpAliases,
                                                                    customHttpAliasesUsed,
                                                                    out customAliasUsed);

                        //process each entry for the alias
                        foreach (string httpAlias in usingHttpAliases)
                        {
                            //string httpAlias = portalAlias.HTTPAlias;
                            //761 : allow duplicate tab paths between culture-specific aliases
                            //this is done by ascertaining which culture a particular alias belongs to
                            //then checking tab cultures as they are added to the dictionary
                            string aliasCulture = "";
                            if (chosenAliasesCultures.ContainsKey(httpAlias.ToLowerInvariant()))
                            {
                                aliasCulture = chosenAliasesCultures[httpAlias.ToLowerInvariant()];
                            }
                            bool ignoreTabWrongCulture = false;
                            //the tab is the wrong culture, so don't add it to the dictionary

                            if (aliasCulture != "")
                            {
                                if (tabCulture != aliasCulture
                                    //this is a language-specific alias that's different to the culture for this alias
                                    && !string.IsNullOrEmpty(tabCulture) //and the tab culture is set
                                    && aliasSpecificCultures.Contains(tabCulture))
                                //and there is a specific alias for this tab culture
                                {
                                    ignoreTabWrongCulture = true;
                                }
                            }
                            if (!ignoreTabWrongCulture)
                            {
                                if (!isExcluded)
                                {
                                    //Add this tab to the dictionary 
                                    //750 : user profile action not returned as buildPortalId not used
                                    tabPathDepth = AddTabToTabDict(tabIndex,
                                                                    dupCheck,
                                                                    httpAlias,
                                                                    aliasCulture,
                                                                    customHttpAlias,
                                                                    thisPortal,
                                                                    tabPath,
                                                                    ref customHttpAliasesUsed,
                                                                    tab,
                                                                    settings,
                                                                    options,
                                                                    homeTabId,
                                                                    ref homePageSkins,
                                                                    parentTraceId);
                                }
                                else
                                {
                                    //589 : custom redirects added as 200 status not causing base urls to redirect
                                    bool excludeFriendlyUrls = true;
                                    //549 : detect excluded friendly urls by putting a known pattern into the dictionary
                                    //add this tab to the dictionary, but with the hack pattern [UseBase] to capture the fact it's a base Url
                                    //then, if there's redirects for it, add those as well.  It's possible to exclude a tab from friendly urls, but 
                                    //give it custom redirects
                                    string rewritePath = null;
                                    if (tab.TabUrls.Count > 0)
                                    {
                                        rewritePath = CreateRewritePath(tab.TabID, "");
                                        string rewritePathKeep = rewritePath; //remember this value to compare
                                        AddCustomRedirectsToDictionary(tabIndex,
                                                                        dupCheck,
                                                                        httpAlias,
                                                                        tab,
                                                                        settings,
                                                                        options,
                                                                        ref rewritePath,
                                                                        out tabPathDepth,
                                                                        ref customHttpAliasesUsed,
                                                                        tab.IsDeleted,
                                                                        parentTraceId);
                                        if (rewritePath != rewritePathKeep)
                                        //check to see the rewrite path is still the same, or did it get changed?
                                        {
                                            //OK, the rewrite path was modifed by the custom redirects dictionary add
                                            excludeFriendlyUrls = false;
                                        }
                                    }

                                    if (excludeFriendlyUrls)
                                    {
                                        rewritePath = "[UseBase]";
                                        //use hack pattern to indicate not to rewrite on this Url
                                    }

                                    AddToTabDict(tabIndex,
                                                    dupCheck,
                                                    httpAlias,
                                                    tab.TabPath,
                                                    rewritePath,
                                                    tab.TabID,
                                                    UrlEnums.TabKeyPreference.TabRedirected,
                                                    ref tabPathDepth,
                                                    true,
                                                    false);
                                }
                            }
                            else
                            {
                                //ignoring this tab because the alias culture doesn't match to the tab culture
                                //however, we need to add it to the dictionary in case there's an old link (pre-translation/pre-friendly url/pre-alias&culture linked) 
                                string rewritePath = CreateRewritePath(tab.TabID, tabCulture);
                                AddToTabDict(tabIndex,
                                                dupCheck,
                                                httpAlias,
                                                tab.TabPath,
                                                rewritePath,
                                                tab.TabID,
                                                UrlEnums.TabKeyPreference.TabRedirected,
                                                ref tabPathDepth,
                                                true,
                                                tab.IsDeleted);
                            }
                            pathSizes.SetTabPathDepth(tabPathDepth);
                        }
                        if (customHttpAlias != "" && customAliasUsed == false &&
                            usingHttpAliases.Contains(customHttpAlias))
                        {
                            //this was using a custom Http Alias, so remove this from the using list if it wasn't already there
                            usingHttpAliases.Remove(customHttpAlias);
                        }
                    }
                }
                //now build the standard Urls for all of the aliases that are used
                foreach (string httpAlias in usingHttpAliases)
                {
                    //750 : using -1 instead of buildPortalId
                    //850 : set culture code based on httpALias, where specific culture 
                    //is being associated with httpAlias
                    string cultureCode = null;
                    if (chosenAliasesCultures.ContainsKey(httpAlias))
                    {
                        cultureCode = chosenAliasesCultures[httpAlias];
                    }
                    AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode);
                }
                //and for any custom urls being used
                foreach (string httpAlias in customHttpAliasesUsed)
                {
                    //750 : using -1 instead of buildPortalId
                    //is being associated with httpAlias
                    string cultureCode = null;
                    if (chosenAliasesCultures.ContainsKey(httpAlias))
                    {
                        cultureCode = chosenAliasesCultures[httpAlias];
                    }
                    AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode);
                    //if any site root, add those as well. So if any module providers or rules work
                    //on the custom http aliases, they will work as well.
                    if (hasSiteRootRedirect)
                    {
                        int tempPathDepth = 0;
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        httpAlias,
                                        "*",
                                        "",
                                        -1,
                                        UrlEnums.TabKeyPreference.TabOK,
                                        ref tempPathDepth,
                                        false,
                                        false);
                    }
                }

                //do a check of the rebuildData object, to see if there is anything we needed to add to the dictionary
                var rebuildData = (PageIndexData)DataCache.GetCache("rebuildData");
                if (rebuildData != null)
                {
                    //there was rebuild data stored so we could do things post-dictionary rebuild
                    if (rebuildData.LastPageKey != null && rebuildData.LastPageValue != null)
                    {
                        if (tabIndex.ContainsKey(rebuildData.LastPageKey) == false)
                        {
                            //add this item to the list of pages, even though it no longer exists
                            tabIndex.Add(rebuildData.LastPageKey, rebuildData.LastPageValue);
                        }
                    }
                    //now clear out the rebuildData object, because we've checked and used it
                    DataCache.RemoveCache("rebuildData");
                }
            }
            return tabIndex;
        }
        private static void AddToTabDict(SharedDictionary<string, string> tabIndex,
                                            Dictionary<string, DupKeyCheck> dupCheckDict,
                                            string httpAlias,
                                            string tabPath,
                                            string rewrittenPath,
                                            int tabId,
                                            UrlEnums.TabKeyPreference keyDupAction,
                                            ref int tabPathDepth,
                                            bool checkForDupUrls,
                                            bool isDeleted)
        {
            //remove leading '/' and convert to lower for all keys 
            string tabPathSimple = tabPath.Replace("//", "/").ToLower();
            //the tabpath depth is only set if it's higher than the running highest tab path depth
            int thisTabPathDepth = tabPathSimple.Length - tabPathSimple.Replace("/", "").Length;
            if (thisTabPathDepth > tabPathDepth)
            {
                tabPathDepth = thisTabPathDepth;
            }
            if ((tabPathSimple.Length > 0 && tabPathSimple[0] == '/'))
            {
                tabPathSimple = tabPathSimple.Substring(1);
            }

            //Contruct the tab key for the dictionary. Using :: allows for separation of portal alias and tab path. 
            string tabKey = (httpAlias + "::" + tabPathSimple).ToLower();

            //construct the duplicate key check
            string dupKey = (httpAlias + "/" + tabPathSimple).ToLower();
            if (dupKey[dupKey.Length - 1] != '/')
            {
                dupKey += "/";
            }

            //now make sure there is NEVER a duplicate key exception by testing for existence first
            using (tabIndex.GetWriteLock())
            {
                if (tabIndex.ContainsKey(tabKey))
                {
                    //it's possible for a tab to be deleted and the tab path repeated. 
                    //the dictionary must be checked to ascertain whether the existing tab 
                    //should be replaced or not.  If the action is 'TabOK' it means
                    //replace the entry regardless.  If the action is 'TabRedirected' it means
                    //replace the existing dictionary ONLY if the existing dictionary entry is a 
                    //deleted tab.
                    bool replaceTab = (keyDupAction == UrlEnums.TabKeyPreference.TabOK); //default, replace the tab
                    if (replaceTab == false)
                    {
                        //ok, the tab to be added is either a redirected or deleted tab
                        //get the existing entry
                        //775 : don't assume that the duplicate check dictionary has the key
                        if (dupCheckDict.ContainsKey(dupKey))
                        {
                            DupKeyCheck foundTab = dupCheckDict[dupKey];
                            //a redirected tab will replace a deleted tab
                            if (foundTab.IsDeleted && keyDupAction == UrlEnums.TabKeyPreference.TabRedirected)
                            {
                                replaceTab = true;
                            }
                            if (foundTab.TabIdOriginal == "-1")
                            {
                                replaceTab = true;
                            }
                        }
                    }
                    if (replaceTab && !isDeleted) //don't replace if the incoming tab is deleted
                    {
                        //remove the previous one 
                        tabIndex.Remove(tabKey);
                        //add the new one 
                        tabIndex.Add(tabKey, Globals.glbDefaultPage + rewrittenPath);
                    }
                }
                else
                {
                    //just add the tabkey into the dictionary
                    tabIndex.Add(tabKey, Globals.glbDefaultPage + rewrittenPath);
                }
            }

            //checking for duplicates means throwing an exception when one is found, but this is just logged to the event log
            if (dupCheckDict.ContainsKey(dupKey))
            {
                DupKeyCheck foundTAb = dupCheckDict[dupKey];
                if ((foundTAb.IsDeleted == false && isDeleted == false) //found is not deleted, this tab is not deleted
                    && keyDupAction == UrlEnums.TabKeyPreference.TabOK
                    && foundTAb.TabIdOriginal != "-1")
                //-1 tabs are login, register, privacy etc
                {
                    //check whether to log for this or not
                    if (checkForDupUrls && foundTAb.TabIdOriginal != tabId.ToString())
                    //dont' show message for where same tab is being added twice)
                    {
                        //there is a naming conflict where this alias/tab path could be mistaken 
                        int tabIdOriginal;
                        string tab1Name = "", tab2Name = "";
                        if (int.TryParse(foundTAb.TabIdOriginal, out tabIdOriginal))
                        {
                            Dictionary<int, int> portalDic = PortalController.GetPortalDictionary();
                            int portalId = -1;
                            if (portalDic != null && portalDic.ContainsKey(tabId))
                            {
                                portalId = portalDic[tabId];
                            }

                            var tc = new TabController();
                            TabInfo tab1 = tc.GetTab(tabIdOriginal, portalId, false);
                            TabInfo tab2 = tc.GetTab(tabId, portalId, false);
                            if (tab1 != null)
                            {
                                tab1Name = tab1.TabName + " [" + tab1.TabPath + "]";
                            }
                            if (tab2 != null)
                            {
                                tab2Name = tab2.TabName + " [" + tab2.TabPath + "]";
                            }
                        }

                        string msg = "Page naming conflict. Url of (" + foundTAb.TabPath +
                                     ") resolves to two separate pages (" + tab1Name + " [tabid = " +
                                     foundTAb.TabIdOriginal + "], " + tab2Name + " [tabid = " + tabId.ToString() +
                                     "]). Only the second page will be shown for the url.";
                        const string msg2 = "PLEASE NOTE : this is an information message only, this message does not affect site operations in any way.";

                        //771 : change to admin alert instead of exception
                        var elc = new EventLogController();
                        //log a host alert
                        var logValue = new LogInfo { LogTypeKey = "HOST_ALERT" };
                        logValue.AddProperty("Advanced Friendly URL Provider Duplicate URL Warning", "Page Naming Conflict");
                        logValue.AddProperty("Duplicate Page Details", msg);
                        logValue.AddProperty("Warning Information", msg2);
                        logValue.AddProperty("Suggested Action", "Rename one or both of the pages to ensure a unique URL");
                        logValue.AddProperty("Hide this message", "To stop this message from appearing in the log, uncheck the option for 'Produce an Exception in the Site Log if two pages have the same name/path?' in the Advanced Url Rewriting settings.");
                        logValue.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                        elc.AddLog(logValue);
                    }
                }
                else
                {
                    dupCheckDict.Remove(dupKey);
                    //add this tab to the duplicate key dictionary 
                    dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted));
                }
            }
            else
            {
                //add this tab to the duplicate key dictionary - the dup key check dict is always maintained 
                //regardless of whether checking is employed or not
                dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted));
            }
        }
        /// <summary>
        /// For the supplied options, return a tab path for the specified tab
        /// </summary>
        /// <param name="tab">TabInfo object of selected tab</param>
        /// <param name="settings">FriendlyUrlSettings</param>
        /// <param name="options"></param>
        /// <param name="ignoreCustomRedirects">Whether to add in the customised Tab redirects or not</param>
        /// <param name="homePageSiteRoot"></param>
        /// <param name="isHomeTab"></param>
        /// <param name="cultureCode"></param>
        /// <param name="isDefaultCultureCode"></param>
        /// <param name="hasPath"></param>
        /// <param name="dropLangParms"></param>
        /// <param name="customHttpAlias"></param>
        /// <param name="isCustomPath"></param>
        /// <param name="parentTraceId"></param>
        /// <remarks>751 : include isDefaultCultureCode flag to determine when using the portal default language
        /// 770 : include custom http alias output for when the Url uses a specific alias due to custom Url rules
        ///  : include new out parameter 'isCustomPath' to return whether the Url was generated from Url-Master custom url
        /// </remarks>
        /// <returns>The tab path as specified</returns>
        internal static string GetTabPath(TabInfo tab,
                                          FriendlyUrlSettings settings,
                                          FriendlyUrlOptions options,
                                          bool ignoreCustomRedirects,
                                          bool homePageSiteRoot,
                                          bool isHomeTab,
                                          string cultureCode,
                                          bool isDefaultCultureCode,
                                          bool hasPath,
                                          out bool dropLangParms,
                                          out string customHttpAlias,
                                          out bool isCustomPath,
                                          Guid parentTraceId)
        {
            string newTabPath;

            dropLangParms   = false;
            customHttpAlias = null;
            isCustomPath    = false;
            if (homePageSiteRoot && isHomeTab && !hasPath)
            // && !isDefaultCultureCode - not working for non-language specifc custom root urls
            {
                newTabPath = "/"; //site root for home page
            }
            else
            {
                //build the tab path and check for space replacement
                string baseTabPath = TabIndexController.GetTabPath(tab, options, parentTraceId);

                //this is the new tab path
                newTabPath = baseTabPath;
                //871 : case insensitive compare for culture code, all lookups done on lower case
                string cultureCodeKey = "";
                if (cultureCode != null)
                {
                    cultureCodeKey = cultureCode.ToLower();
                }

                bool checkForCustomHttpAlias = false;
                //get a custom tab name if redirects are being used
                SharedDictionary <string, string> customAliasForTabs = null;
                SharedDictionary <int, SharedDictionary <string, string> > urlDict;
                //886 : don't fetch custom urls for host tabs (host tabs can't have redirects or custom Urls)
                if (tab.PortalID > -1)
                {
                    urlDict = CustomUrlDictController.FetchCustomUrlDictionary(tab.PortalID, false, false, settings, out customAliasForTabs, parentTraceId);
                }
                else
                {
                    urlDict = new SharedDictionary <int, SharedDictionary <string, string> >();
                    //create dummy dictionary for this tab
                }

                if (ignoreCustomRedirects == false)
                {
                    //if not ignoring the custom redirects, look for the Url of the page in this list
                    //this will be used as the page path if there is one.

                    using (urlDict.GetReadLock())
                    {
                        if (urlDict.ContainsKey(tab.TabID))
                        {
                            //we want the custom value
                            string customTabPath = null;
                            SharedDictionary <string, string> tabpaths = urlDict[tab.TabID];

                            using (tabpaths.GetReadLock())
                            {
                                if (tabpaths.ContainsKey(cultureCodeKey))
                                {
                                    customTabPath = tabpaths[cultureCodeKey];
                                    dropLangParms = true;
                                    //the url is based on a custom value which has embedded language parms, therefore don't need them in the url
                                }
                                else
                                {
                                    if (isDefaultCultureCode && tabpaths.ContainsKey(""))
                                    {
                                        customTabPath = tabpaths[""];
                                        //dropLangParms = true;//drop the language parms if they exist, because this is the default language
                                    }
                                }
                            }
                            if (customTabPath != null)
                            {
                                //770 : pull out custom http alias if in string
                                int aliasSeparator = customTabPath.IndexOf("::", StringComparison.Ordinal);
                                if (aliasSeparator > 0)
                                {
                                    customHttpAlias = customTabPath.Substring(0, aliasSeparator);
                                    newTabPath      = customTabPath.Substring(aliasSeparator + 2);
                                }
                                else
                                {
                                    newTabPath = customTabPath;
                                }
                            }
                            if (newTabPath == "" && hasPath)
                            {
                                //can't pass back a custom path which is blank if there are path segments to the requested final Url
                                newTabPath = baseTabPath; //revert back to the standard DNN page path
                            }
                            else
                            {
                                isCustomPath = true; //we are providing a custom Url
                            }
                        }
                        else
                        {
                            checkForCustomHttpAlias = true;
                        }
                    }
                }
                else
                {
                    checkForCustomHttpAlias = true;
                    //always want to check for custom alias, even when we don't want to see any custom redirects
                }

                //770 : check for custom alias in these tabs
                if (checkForCustomHttpAlias && customAliasForTabs != null)
                {
                    string key = tab.TabID.ToString() + ":" + cultureCodeKey;
                    using (customAliasForTabs.GetReadLock())
                    {
                        if (customAliasForTabs.ContainsKey(key))
                        {
                            //this tab uses a custom alias
                            customHttpAlias = customAliasForTabs[key];
                            isCustomPath    = true; //using custom alias
                        }
                    }
                }

                if (!dropLangParms)
                {
                    string tabCultureCode = tab.CultureCode;
                    if (!string.IsNullOrEmpty(tabCultureCode))
                    {
                        dropLangParms = true;
                        //if the tab has a specified culture code, then drop the language parameters from the friendly Url
                    }
                }
                //make lower case if necessary
                newTabPath = AdvancedFriendlyUrlProvider.ForceLowerCaseIfAllowed(tab, newTabPath, settings);
            }
            return(newTabPath);
        }
示例#13
0
        /// <summary>
        /// Returns a list of tab and redirects from the database, for the specified portal
        /// Assumes that the dictionary should have any existing items replaced if the portalid is specified
        /// and the portal tabs already exist in the dictionary.
        /// </summary>
        /// <param name="existingTabs"></param>
        /// <param name="portalId"></param>
        /// <param name="settings"></param>
        /// <param name="customAliasTabs"></param>
        /// <remarks>
        ///    Each dictionary entry in the return value is a complex data type of another dictionary that is indexed by the url culture.  If there is
        ///    only one culture for the Url, it will be that culture.
        /// </remarks>
        /// <returns></returns>
        private static SharedDictionary <int, SharedDictionary <string, string> > BuildUrlDictionary(SharedDictionary <int, SharedDictionary <string, string> > existingTabs,
                                                                                                     int portalId,
                                                                                                     FriendlyUrlSettings settings,
                                                                                                     ref SharedDictionary <string, string> customAliasTabs)
        {
            //fetch tabs with redirects
            var tabs = FriendlyUrlController.GetTabs(portalId, false, null, settings);

            if (existingTabs == null)
            {
                existingTabs = new SharedDictionary <int, SharedDictionary <string, string> >();
            }
            if (customAliasTabs == null)
            {
                customAliasTabs = new SharedDictionary <string, string>();
            }


            //go through each tab in the found list
            foreach (TabInfo tab in tabs.Values)
            {
                //check the custom alias tabs collection and add to the dictionary where necessary
                foreach (var customAlias in tab.CustomAliases)
                {
                    string key = tab.TabID.ToString() + ":" + customAlias.Key;
                    using (customAliasTabs.GetWriteLock())  //obtain write lock on custom alias Tabs
                    {
                        if (customAliasTabs.ContainsKey(key) == false)
                        {
                            customAliasTabs.Add(key, customAlias.Value);
                        }
                    }
                }

                foreach (TabUrlInfo redirect in tab.TabUrls)
                {
                    if (redirect.HttpStatus == "200")
                    {
                        string url = redirect.Url;
                        //770 : add in custom alias into the tab path for the custom Urls
                        if (redirect.PortalAliasUsage != PortalAliasUsageType.Default && redirect.PortalAliasId > 0)
                        {
                            //there is a custom http alias specified for this portal alias
                            var             pac   = new PortalAliasController();
                            PortalAliasInfo alias = pac.GetPortalAliasByPortalAliasID(redirect.PortalAliasId);
                            if (alias != null)
                            {
                                string customHttpAlias = alias.HTTPAlias;
                                url = customHttpAlias + "::" + url;
                            }
                        }
                        string cultureKey = redirect.CultureCode.ToLower();
                        int    tabid      = tab.TabID;
                        using (existingTabs.GetWriteLock())
                        {
                            if (existingTabs.ContainsKey(tabid) == false)
                            {
                                var entry = new SharedDictionary <string, string>();
                                using (entry.GetWriteLock())
                                {
                                    entry.Add(cultureKey, url);
                                }
                                //871 : use lower case culture code as key
                                existingTabs.Add(tab.TabID, entry);
                            }
                            else
                            {
                                SharedDictionary <string, string> entry = existingTabs[tabid];
                                //replace tab if existing but was retreieved from tabs call
                                if (tab.PortalID == portalId || portalId == -1)
                                {
                                    using (entry.GetWriteLock())
                                    {
                                        if (entry.ContainsKey(cultureKey) == false)
                                        {
                                            //add the culture and set in parent dictionary
                                            //871 : use lower case culture code as key
                                            entry.Add(cultureKey, url);
                                            existingTabs[tabid] = entry;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(existingTabs);
        }
示例#14
0
        private static string CheckIfPortalAlias(string url, NameValueCollection querystringCol, UrlAction result, FriendlyUrlSettings settings, SharedDictionary<string, string> tabDict)
        {
            string newUrl = url;
            bool reWritten = false;

            string defaultPage = Globals.glbDefaultPage.ToLower();
            string portalAliasUrl = url.ToLower().Replace("/" + defaultPage, "");
            //if there is a straight match on a portal alias, it's the home page for that portal requested 
            var portalAlias = PortalAliasController.GetPortalAliasInfo(portalAliasUrl);
            if (portalAlias != null)
            {
                //special case : sometimes, some servers issue root/default.aspx when root/ was requested, sometimes not.  It depends
                //on other server software installed (apparently)
                //so check the raw Url and the url, and see if they are the same except for the /default.aspx
                string rawUrl = result.RawUrl;
                if (url.ToLower().EndsWith(rawUrl + defaultPage.ToLower()))
                {
                    //special case - change the url to be equal to the raw Url
                    url = url.Substring(0, url.Length - defaultPage.Length);
                }

                if (settings.RedirectDefaultPage
                    && url.ToLower().EndsWith("/" + defaultPage)
                    && result.RedirectAllowed)
                {
                    result.Reason = RedirectReason.Site_Root_Home;
                    result.FinalUrl = Globals.AddHTTP(portalAliasUrl + "/");
                    result.Action = ActionType.Redirect301;
                }
                else
                {
                    //special case -> look in the tabdict for a blank intercept
                    //735 : switch to custom method for getting portal
                    PortalInfo portal = CacheController.GetPortal(portalAlias.PortalID, true);
                    if (portal.HomeTabId == -1)
                    {
                        string tabKey = url;
                        if (tabKey.EndsWith("/"))
                        {
                            tabKey = tabKey.TrimEnd('/');
                        }
                        tabKey += "::";
                        using (tabDict.GetReadLock())
                        {
                            if (tabDict.ContainsKey(tabKey))
                            {
                                newUrl = tabDict[tabKey];
                                reWritten = true;
                            }
                        }
                        //if no home tab, but matched a portal alias, and no trailing /default.aspx
                        //and no 'newUrl' value because not rewritten, then append the /default.aspx 
                        //and ask for a rewrite on that one.
                        //DNNDEV-27291
                        if (reWritten == false)
                        {
                            newUrl = "/" + DotNetNuke.Common.Globals.glbDefaultPage;
                            reWritten = true;
                        }
                    }
                    else
                    {
                        //set rewrite to home page of site
                        //760: check for portal alias specific culture before choosing home tabid
                        bool checkForCustomAlias = false;
                        bool customTabAlias = false;
                        //check for culture-specific aliases
                        string culture = null;
                        var primaryAliases = TestablePortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList();
                        //if there are chosen portal aliases, check to see if the found alias is one of them
                        //if not, then will check for a custom alias per tab
                        if (primaryAliases.ContainsAlias(portal.PortalID, portalAlias.HTTPAlias) == false)
                        {
                            checkForCustomAlias = true;
                        }
                        else
                        {
                            //check for a specific culture for the alias
                            culture = primaryAliases.GetCultureByPortalIdAndAlias(portal.PortalID, portalAlias.HTTPAlias);
                        }
                        if (checkForCustomAlias)
                        {
                            //ok, this isnt' a chosen portal alias, check the list of custom aliases
                            List<string> customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings);
                            if (customAliasesForTabs != null && customAliasesForTabs.Contains(portalAlias.HTTPAlias.ToLower()))
                            {
                                //ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context
                                string tabKey = url.ToLower();
                                if (tabKey.EndsWith("/"))
                                {
                                    tabKey = tabKey.TrimEnd('/');
                                }
                                if (tabKey.EndsWith("/default.aspx"))
                                {
                                    tabKey = tabKey.Substring(0, tabKey.Length - 13); //13 = "/default.aspx".length
                                }
                                tabKey += "::";
                                using (tabDict.GetReadLock())
                                {
                                    if (tabDict.ContainsKey(tabKey))
                                    {
                                        newUrl = tabDict[tabKey];
                                        reWritten = true;
                                        customTabAlias = true; //this alias is used as the alias for a custom tab
                                    }
                                }
                            }
                        }
                        if (customTabAlias == false)
                        {
                            int tabId;
                            if (!String.IsNullOrEmpty(querystringCol["TabId"]))
                            {
                                tabId = Convert.ToInt32(querystringCol["TabId"]);
                                result.Action = ActionType.CheckFor301;
                            }
                            else
                            {
                                tabId = portal.HomeTabId;
                                //not a custom alias for a specific tab, so it must be the home page for the portal we identified
                                if (culture == null)
                                {
                                    culture = portal.DefaultLanguage; //set culture to default if not found specifically
                                }
                                else
                                {
                                    //if there is a specific culture for this alias, and it's different to the default language, then
                                    //go check for a specific culture home page (5.5 and later)
                                    tabId = TabPathHelper.GetHomePageTabIdForCulture(portal.DefaultLanguage,
                                                                                         portal.PortalID,
                                                                                         culture,
                                                                                         tabId);
                                }
                            }
                            //see if there is a skin for the alias/culture combination
                            string skin = TabPathHelper.GetTabAliasSkinForTabAndAlias(portalAlias.PortalID,
                                                                                      portalAlias.HTTPAlias, culture);
                            if (string.IsNullOrEmpty(skin) == false)
                            {
                                newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, "", "skinSrc=" + skin);
                            }
                            else
                            {
                                newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, "");
                            }
                            if (culture != portal.DefaultLanguage)
                            {
                                AddLanguageCodeToRewritePath(ref newUrl, culture);
                            }
                            //add on language specified by current portal alias
                            reWritten = true;
                        }
                    }
                }

                if (reWritten)
                {
                    //check for replaced to site root from /default.aspx 
                    // 838  set redirect reason and action from result
                    SetRewriteParameters(ref result, newUrl);
                    ActionType action;
                    RedirectReason reason;
                    string resultingUrl;
                    RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, true, settings, out resultingUrl, out reason, out action);
                    newUrl = resultingUrl;
                    result.Action = action;
                    result.Reason = reason;
                }
            }
            return newUrl;
        }
 private static void AddEntryToDictionary(SharedDictionary<int, SharedDictionary<string, string>> existingTabs, int portalId, TabInfo tab, string cultureKey, string url)
 {
     int tabid = tab.TabID;
     using (existingTabs.GetWriteLock())
     {
         if (existingTabs.ContainsKey(tabid) == false)
         {
             var entry = new SharedDictionary<string, string>();
             using (entry.GetWriteLock())
             {
                 entry.Add(cultureKey, url);
             }
             //871 : use lower case culture code as key
             existingTabs.Add(tab.TabID, entry);
         }
         else
         {
             SharedDictionary<string, string> entry = existingTabs[tabid];
             //replace tab if existing but was retreieved from tabs call
             if (tab.PortalID == portalId || portalId == -1)
             {
                 using (entry.GetWriteLock())
                 {
                     if (entry.ContainsKey(cultureKey) == false)
                     {
                         //add the culture and set in parent dictionary
                         //871 : use lower case culture code as key
                         entry.Add(cultureKey, url);
                         existingTabs[tabid] = entry;
                     }
                 }
             }
         }
     }
 }
示例#16
0
        /// <summary>
        /// Returns a portal info object for the portal
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="exceptionOnNull"></param>
        /// <remarks>This method wraps the PortalController.GetPortal method, and adds a check if the reuslt is null.</remarks>.
        /// <returns></returns>
        public static PortalInfo GetPortal(int portalId, bool exceptionOnNull)
        {
            PortalInfo pi = null;
            //775 : change to use threadsafe dictionary
            SharedDictionary <int, PortalInfo> portals = (SharedDictionary <int, PortalInfo>)DataCache.GetCache(PortalsKey) ??
                                                         new SharedDictionary <int, PortalInfo>();

            using (portals.GetWriteLock())
            {
                if (portals.ContainsKey(portalId))
                {
                    //portal found, return
                    pi = portals[portalId];
                }
                else
                {
                    try
                    {
                        //if not found, get from database
                        pi = PortalController.Instance.GetPortal(portalId);

                        if (pi == null)
                        {
                            // Home page redirect loop when using default language not en-US and first request with secondary language
                            //calls get portal using culture code to support
                            string cultureCode = PortalController.GetActivePortalLanguage(portalId);
                            pi = PortalController.Instance.GetPortal(portalId, cultureCode);
                        }
                        if (pi != null)
                        {
                            // Home page redirect loop when using default language not en-US and first request with secondary language
                            //check for correct, default language code in portal object
                            string portalCultureCode = pi.CultureCode;
                            if (portalCultureCode != null &&
                                String.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0)
                            {
                                //portal culture code and default culture code are not the same.
                                //this means we will get the incorrect home page tab id
                                //call back and get the correct one as per the default language
                                PortalInfo defaultLangPortal = PortalController.Instance.GetPortal(portalId, pi.DefaultLanguage);
                                if (defaultLangPortal != null)
                                {
                                    pi = defaultLangPortal;
                                }
                            }
                        }
                        if (pi != null)
                        {
                            //add to dictionary and re-store in cache
                            portals.Add(pi.PortalID, pi);
                            DataCache.SetCache(PortalsKey, portals); //store back in dictionary
                        }
                    }
// ReSharper disable EmptyGeneralCatchClause
                    catch
// ReSharper restore EmptyGeneralCatchClause
                    {
                        //912: capture as fall back any exception resulting from doing a portal lookup in 6.x
                        //this happens when portalId = -1
                        //no long, no handling, just passonwards with null portal
                    }
                }
            }

            if (exceptionOnNull && pi == null)
            {
                throw new NullReferenceException("No Portal Found for portalid : " + portalId.ToString());
            }
            return(pi);
        }
示例#17
0
        private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrlSettings settings, SharedDictionary<string, string> tabDict, ref string newUrl)
        {
            bool found;
            string userParam = String.Empty;
            string tabLookUpKey = tabKeyVal;
            using (tabDict.GetReadLock())
            {
                found = tabDict.ContainsKey(tabLookUpKey); //lookup the tabpath in the tab dictionary
            }

            //special case, if no extensions and the last part of the tabKeyVal contains default.aspx, then
            //split off the default.aspx part and try again - compensating for gemini issue http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=8651&PROJID=39
            if (!found && settings.PageExtensionUsageType != PageExtensionUsageType.AlwaysUse)
            {
                found = CheckSpecialCase(tabLookUpKey, tabDict);
            }

            //Check for VanityUrl
            var doNotRedirectRegex = new Regex(settings.DoNotRedirectRegex);
            if (!found && !AdvancedUrlRewriter.ServiceApi.IsMatch(result.RawUrl) && !doNotRedirectRegex.IsMatch(result.RawUrl))
            {
                string[] urlParams = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None);
                if (urlParams.Length > 1)
                {
                    //Extract the first Url parameter
                    string tabPath = urlParams[1];

                    var urlSegments = tabPath.Split('/');

                    string prefix = urlSegments[0];

                    if (prefix == settings.VanityUrlPrefix && urlSegments.Length == 2)
                    {
                        string vanityUrl = urlSegments[1];

                        //check if its a vanityUrl
                        var user = GetUser(result.PortalId, vanityUrl);
                        if (user != null)
                        {
                            userParam = "UserId=" + user.UserID.ToString();

                            //Get the User profile Tab
                            var portal = new PortalController().GetPortal(result.PortalId);
                            var profilePage = new TabController().GetTab(portal.UserTabId, result.PortalId, false);

                            FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings);
                            string profilePagePath = TabPathHelper.GetFriendlyUrlTabPath(profilePage, options, Guid.NewGuid());

                            //modify lookup key;
                            tabLookUpKey = tabLookUpKey.Replace("::" + String.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), "::" + profilePagePath.TrimStart('/').ToLowerInvariant());

                            using (tabDict.GetReadLock())
                            {
                                found = tabDict.ContainsKey(tabLookUpKey); //lookup the tabpath in the tab dictionary
                            }
                        }
                    }
                }
            }

            if (found)
            {
                using (tabDict.GetReadLock())
                {
                    //determine what the rewritten URl will be 
                    newUrl = tabDict[tabLookUpKey];
                }
                if (!String.IsNullOrEmpty(userParam))
                {
                    newUrl = newUrl + "&" + userParam;
                }
                //if this is a match on the trigger dictionary rebuild,
                //then temporarily store this value in case it's a page name change
                //677 : only match if is on actual tabKeyVal match, to prevent site root redirects
                //statements were moved into this 'if' statement
                result.dictVal = newUrl;
                result.dictKey = tabKeyVal;
            }
            return found;
        }
示例#18
0
 private static bool CheckSpecialCase(string tabKeyVal, SharedDictionary<string, string> tabDict)
 {
     bool found = false;
     int pathStart = tabKeyVal.LastIndexOf("::", StringComparison.Ordinal); //look for portal alias separator
     int lastPath = tabKeyVal.LastIndexOf('/');
     //get any path separator in the tab path portion
     if (pathStart > lastPath)
     {
         lastPath = pathStart;
     }
     if (lastPath >= 0)
     {
         int defaultStart = tabKeyVal.ToLower().IndexOf("default", lastPath, StringComparison.Ordinal);
         //no .aspx on the end anymore
         if (defaultStart > 0 && defaultStart > lastPath)
         //there is a default in the path, and it's not the entire path (ie pagnamedefault and not default)
         {
             tabKeyVal = tabKeyVal.Substring(0, defaultStart);
             //get rid of the default.aspx part
             using (tabDict.GetReadLock())
             {
                 found = tabDict.ContainsKey(tabKeyVal);
                 //lookup the tabpath in the tab dictionary again
             }
         }
     }
     return found;
 }