/// <summary>
        /// Constructor of the main user interface form
        /// </summary>
        public ApplianceForm()
        {
            // Initialise the components of the GUI
            InitializeComponent();

            // Start feed from Google Spreadsheets
            SpreadSheet s = new SpreadSheet();

            // Set the instance of the shared dictionary
            this.sharedDictionary = ConnectionSingleton.Instance.GetSharedDictionary();
        }
Esempio n. 2
0
 public SharedDictionaryTester(string testName, string path, object o, INamedVersionedUniqueId uid1, INamedVersionedUniqueId uid2, Action <ISharedDictionary, object, INamedVersionedUniqueId> f)
 {
     _errors   = new List <ReadElementObjectInfo>();
     _testName = testName;
     _path     = path;
     _seed     = Environment.TickCount;
     _o        = o;
     _uid1     = uid1;
     _uid2     = uid2;
     _dic      = SharedDictionary.Create(null);
     _seed2    = GenerateRandomProperties(_dic, _o, _uid1, 10, _seed);
     f(_dic, _o, _uid1);
     _seed3 = GenerateRandomProperties(_dic, _o, _uid1, 10, _seed2);
     GenerateRandomProperties(_dic, _o, _uid2, 20, _seed3);
 }
        private const int UserAgentsCacheTimeout = 60;                //user agents cache expire time.(minutes)

        /// <summary>
        ///   Returns ClientCapability based on HttpRequest
        /// </summary>
        public override IClientCapability GetClientCapability(string userAgent)
        {
            DeviceInfoClientCapability deviceInfoClientCapability = null;

            if (!string.IsNullOrEmpty(userAgent))
            {
                bool found = false;

                //try to get content from cache
                var cachedUserAgents = DataCache.GetCache <SharedDictionary <string, DeviceInfoClientCapability> >(UserAgentsCacheKey);
                if (cachedUserAgents != null)
                {
                    using (cachedUserAgents.GetReadLock())
                    {
                        if (cachedUserAgents.ContainsKey(userAgent))
                        {
                            deviceInfoClientCapability = cachedUserAgents[userAgent];
                            found = true;
                        }
                    }
                }

                if (!found)
                {
                    var deviceInfo = WurflProvider.GetDeviceInfo(userAgent);
                    if (deviceInfo != null)
                    {
                        deviceInfoClientCapability = new DeviceInfoClientCapability(deviceInfo);

                        //update cache content
                        if (cachedUserAgents == null)
                        {
                            cachedUserAgents = new SharedDictionary <string, DeviceInfoClientCapability>();
                        }
                        using (cachedUserAgents.GetWriteLock())
                        {
                            cachedUserAgents[userAgent] = deviceInfoClientCapability;
                        }
                        DataCache.SetCache(UserAgentsCacheKey, cachedUserAgents, TimeSpan.FromMinutes(UserAgentsCacheTimeout));
                    }
                }
            }

            var wurflClientCapability = new WURFLClientCapability(deviceInfoClientCapability);

            wurflClientCapability.UserAgent = userAgent;
            return(wurflClientCapability);
        }
        private void RunUserRequest(object args)
        {
            var requestId = "N/A";

            try
            {
                var userRequest = (UserRequestWrapper)args;

                requestId = userRequest.Id;

                try
                {
                    // Heart of the process
                    userRequest.Statement                       // 1. Take a statement
                    .ToWordArray(userRequest.RemovePunctuation) // 2. Split into words with/without removal of punctuation
                    .CountWordOccurences()                      //3. Transform into word-counter pairs
                    .ToList()
                    .ForEach(
                        countedWord =>      // and add each one to dictionary
                    {
                        userRequest.Snapshot = SharedDictionary.CheckIncrement(countedWord.Word, countedWord.Count);
                    });
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("Error processing request id {0}: {1}", requestId, ex.ToString()));
                    userRequest.HasError = true;
                    userRequest.Error    = ex.ToString();
                }
                finally
                {
                    RemoveUserRequest(requestId);
                    try
                    {
                        _servedUserRequests.Release();
                    }
                    catch
                    {
                    }
                    userRequest.WaitForRequestToComplete.Set();
                    userRequest.RequestCompleteAt = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error processing request id {0}: {1}", requestId, ex.ToString()));
            }
        }
Esempio n. 5
0
        public void WriteReadUserConfig()
        {
            string path = Path.Combine(TestFolder, "UserConfig.xml");
            Guid   id   = new Guid("{6AFBAE01-5CD1-4EDE-BB56-4590C5A253DF}");

            // Write ----------------------------------------------------------
            {
                ISharedDictionary      dic    = SharedDictionary.Create(null);
                IConfigManagerExtended config = ConfigurationManager.Create(dic);
                Assert.That(config, Is.Not.Null);
                Assert.That(config.HostUserConfig, Is.Not.Null);
                Assert.That(config.ConfigManager.UserConfiguration, Is.Not.Null);

                config.HostUserConfig["key1"] = "value1";
                config.HostUserConfig["key2"] = "value2";
                config.HostUserConfig["key3"] = "value3";
                config.ConfigManager.UserConfiguration.PluginsStatus.SetStatus(id, ConfigPluginStatus.AutomaticStart);

                Assert.That(config.IsUserConfigDirty);
                Assert.That(config.IsSystemConfigDirty, Is.False);

                using (Stream wrt = new FileStream(path, FileMode.Create))
                    using (IStructuredWriter sw = SimpleStructuredWriter.CreateWriter(wrt, null))
                    {
                        config.SaveUserConfig(sw);
                    }
            }

            // Read ------------------------------------------------------------
            {
                ISimpleServiceContainer container = new SimpleServiceContainer();
                ISharedDictionary       dic       = SharedDictionary.Create(container);
                IConfigManagerExtended  config    = ConfigurationManager.Create(dic);

                using (Stream str = new FileStream(path, FileMode.Open))
                    using (IStructuredReader sr = SimpleStructuredReader.CreateReader(str, container))
                    {
                        config.LoadUserConfig(sr);
                    }
                Assert.That(config.HostUserConfig["key1"], Is.EqualTo("value1"));
                Assert.That(config.HostUserConfig["key2"], Is.EqualTo("value2"));
                Assert.That(config.HostUserConfig["key3"], Is.EqualTo("value3"));
                Assert.That(config.ConfigManager.UserConfiguration.PluginsStatus.GetStatus(id, ConfigPluginStatus.Disabled) == ConfigPluginStatus.AutomaticStart);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Store the Url Dictionary (all tab urls / tabids) for the installation.
        /// </summary>
        /// <param name="urlDict"></param>
        /// <param name="urlPortals"></param>
        /// <param name="customAliasTabs"></param>
        /// <param name="settings"></param>
        /// <param name="reason"></param>
        /// <remarks>
        /// </remarks>
        internal void StoreFriendlyUrlIndexInCache(
            SharedDictionary <int, SharedDictionary <string, string> > urlDict,
            ConcurrentBag <int> urlPortals,
            SharedDictionary <string, string> customAliasTabs,
            FriendlyUrlSettings settings,
            string reason)
        {
            if (settings.LogCacheMessages)
            {
                this.onRemovePageIndex = this.RemovedPageIndexCallBack;
            }
            else
            {
                this.onRemovePageIndex = null;
            }

            LogRemovedReason = settings.LogCacheMessages;

            SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(this.GetTabsCacheDependency(urlPortals)), settings, this.onRemovePageIndex);
            SetPageCache(UrlPortalsKey, urlPortals, settings);
            SetPageCache(CustomAliasTabsKey, customAliasTabs, settings);

            if (settings.LogCacheMessages)
            {
                var log = new LogInfo {
                    LogTypeKey = "HOST_ALERT"
                };
                log.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache.");
                log.AddProperty("Build Reason", reason);
                log.AddProperty("Cache Key", UrlDictKey);
                using (urlDict.GetReadLock())
                {
                    log.AddProperty("Item Count", urlDict.Values.Count.ToString());
                }

                log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                log.AddProperty("Item added to cache", "Url Portals object added to cache.  Key:" + UrlPortalsKey + "  Items: " + urlPortals.Count.ToString());
                using (customAliasTabs.GetReadLock())
                {
                    log.AddProperty("Item added to cache", "Custom Alias Tabs added to cache.  Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString());
                }

                LogController.Instance.AddLog(log);
            }
        }
Esempio n. 7
0
        public void TestProductionSharedDictionary5()
        {
            var runtime = RuntimeFactory.Create();
            var counter = SharedDictionary.Create <int, string>(runtime);
            var tcs1    = new TaskCompletionSource <bool>();
            var failed  = false;

            runtime.OnFailure += (ex) =>
            {
                failed = true;
                tcs1.SetResult(true);
            };

            var m1 = runtime.CreateActor(typeof(M5), new E(counter, tcs1));

            Task.WaitAll(tcs1.Task);
            Assert.False(failed);
        }
        public void TestDictionarySuccess()
        {
            var runtime = PSharpRuntime.Create();
            var counter = SharedDictionary.Create <int, string>(runtime);
            var tcs1    = new TaskCompletionSource <bool>();
            var failed  = false;

            runtime.OnFailure += delegate
            {
                failed = true;
                tcs1.SetResult(true);
            };

            var m1 = runtime.CreateMachine(typeof(M), new E(counter, tcs1));

            Task.WaitAll(tcs1.Task);
            Assert.False(failed);
        }
Esempio n. 9
0
        internal void GetPageIndexFromCache(out SharedDictionary <string, string> dict,
                                            out SharedDictionary <int, PathSizes> portalDepthInfo,
                                            FriendlyUrlSettings settings)
        {
            object raw = DataCache.GetCache(PageIndexKey);

            if (raw != null)
            {
                dict            = (SharedDictionary <string, string>)raw;
                raw             = DataCache.GetCache(PageIndexDepthKey);
                portalDepthInfo = (SharedDictionary <int, PathSizes>)raw;
            }
            else
            {
                dict            = null;
                portalDepthInfo = null;
            }
        }
Esempio n. 10
0
        public void WriteReadSystemConfig()
        {
            string path = Path.Combine(TestFolder, "SystemConfig.xml");

            // Write ----------------------------------------------------------
            {
                ISharedDictionary      dic    = SharedDictionary.Create(null);
                IConfigManagerExtended config = ConfigurationManager.Create(dic);

                Assert.That(config.ConfigManager.SystemConfiguration != null);

                config.HostSystemConfig["key1"] = "value1";
                config.HostSystemConfig["key2"] = "value2";
                config.HostSystemConfig["key3"] = "value3";
                config.HostSystemConfig["{12A9FCC0-ECDC-4049-8DBF-8961E49A9EDE}"] = true;

                Assert.That(config.IsSystemConfigDirty);
                Assert.That(config.IsUserConfigDirty, Is.False);

                using (Stream wrt = new FileStream(path, FileMode.Create))
                    using (IStructuredWriter sw = SimpleStructuredWriter.CreateWriter(wrt, null))
                    {
                        config.SaveSystemConfig(sw);
                    }
            }
            TestBase.DumpFileToConsole(path);
            // Read ------------------------------------------------------------
            {
                ISharedDictionary      dic    = SharedDictionary.Create(null);
                IConfigManagerExtended config = new ConfigManagerImpl(dic);

                using (Stream str = new FileStream(path, FileMode.Open))
                    using (IStructuredReader sr = SimpleStructuredReader.CreateReader(str, null))
                    {
                        config.LoadSystemConfig(sr);
                    }
                Assert.That(config.HostSystemConfig["key1"], Is.EqualTo("value1"));
                Assert.That(config.HostSystemConfig["key2"], Is.EqualTo("value2"));
                Assert.That(config.HostSystemConfig["key3"], Is.EqualTo("value3"));
                Assert.That(config.HostSystemConfig["{12A9FCC0-ECDC-4049-8DBF-8961E49A9EDE}"], Is.EqualTo(true));
            }
        }
Esempio n. 11
0
        private void SetUrlInCache(string cacheKey, string url)
        {
            if (string.IsNullOrEmpty(cacheKey))
            {
                return;
            }

            var cachedUrls = DataCache.GetCache <SharedDictionary <string, string> >(UrlsCacheKey);

            if (cachedUrls == null)
            {
                cachedUrls = new SharedDictionary <string, string>();
            }
            using (cachedUrls.GetWriteLock())
            {
                cachedUrls[cacheKey] = url;
            }

            DataCache.SetCache(UrlsCacheKey, cachedUrls, TimeSpan.FromMinutes(UrlsCacheTimeout));
        }
Esempio n. 12
0
        private TabInfo(SharedDictionary <string, string> localizedTabNameDictionary, SharedDictionary <string, string> fullUrlDictionary)
        {
            this._localizedTabNameDictionary = localizedTabNameDictionary;
            this._fullUrlDictionary          = fullUrlDictionary;

            this.PortalID            = Null.NullInteger;
            this._authorizedRoles    = Null.NullString;
            this.ParentId            = Null.NullInteger;
            this.IconFile            = Null.NullString;
            this.IconFileLarge       = Null.NullString;
            this._administratorRoles = Null.NullString;
            this.Title           = Null.NullString;
            this.Description     = Null.NullString;
            this.KeyWords        = Null.NullString;
            this.Url             = Null.NullString;
            this.SkinSrc         = Null.NullString;
            this._skinDoctype    = Null.NullString;
            this.ContainerSrc    = Null.NullString;
            this.TabPath         = Null.NullString;
            this.StartDate       = Null.NullDate;
            this.EndDate         = Null.NullDate;
            this.RefreshInterval = Null.NullInteger;
            this.PageHeadText    = Null.NullString;
            this.SiteMapPriority = 0.5F;

            // UniqueId, Version Guid, and Localized Version Guid should be initialised to a new value
            this.UniqueId             = Guid.NewGuid();
            this.VersionGuid          = Guid.NewGuid();
            this.LocalizedVersionGuid = Guid.NewGuid();

            // Default Language Guid should be initialised to a null Guid
            this.DefaultLanguageGuid = Null.NullGuid;

            this.IsVisible        = true;
            this.HasBeenPublished = true;
            this.DisableLink      = false;

            this.Panes = new ArrayList();

            this.IsSystem = false;
        }
Esempio n. 13
0
        internal void StorePageIndexInCache(
            SharedDictionary <string, string> tabDictionary,
            SharedDictionary <int, PathSizes> portalDepthInfo,
            FriendlyUrlSettings settings,
            string reason)
        {
            this.onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback)this.RemovedPageIndexCallBack : null;

            // get list of portal ids for the portals we are storing in the page index
            var portalIds = new List <int>();

            using (portalDepthInfo.GetReadLock())
            {
                portalIds.AddRange(portalDepthInfo.Keys);
            }

            // 783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex.
            SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(this.GetTabsCacheDependency(portalIds)), settings, this.onRemovePageIndex);

            SetPageCache(PageIndexDepthKey, portalDepthInfo, settings);

            LogRemovedReason = settings.LogCacheMessages;

            if (settings.LogCacheMessages)
            {
                var log = new LogInfo {
                    LogTypeKey = "HOST_ALERT"
                };

                log.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache");
                log.AddProperty("Reason", reason);
                log.AddProperty("Cache Item Key", PageIndexKey);
                using (tabDictionary.GetReadLock())
                {
                    log.AddProperty("Item Count", tabDictionary.Count.ToString());
                }

                log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                LogController.Instance.AddLog(log);
            }
        }
Esempio n. 14
0
        public void ImportReloadedSkippedFragments()
        {
            INamedVersionedUniqueId uid1 = SharedDicTestContext.Plugins[0];
            INamedVersionedUniqueId uid2 = SharedDicTestContext.Plugins[1];

            string path = TestBase.GetTestFilePath("SharedDic", "ImportReloadedSkippedFragments");

            #region Creates actual fragments

            // Creates a dummy dictionnary and writes it.
            SharedDictionaryImpl dic = CreateDummySharedDic(this, uid1, uid2);
            SharedDicTestContext.Write("Test", path, dic, this);

            // Creates a second dictionnary to load previous data (with skippedFragments).
            IList <ReadElementObjectInfo> errors;
            SharedDictionaryImpl          dicFrag = (SharedDictionaryImpl)SharedDicTestContext.Read("Test", path, this, out errors);
            Assert.IsTrue(new FileInfo(path).Length > 0, "File must exist and be not empty.");

            Assert.That(errors.Count, Is.EqualTo(0));
            Assert.That(dicFrag.GetSkippedFragments(this).Count == 2);
            Assert.That(dicFrag[this, uid1, "key1"], Is.Null);
            Assert.That(dicFrag[this, uid2, "key2"], Is.Null);

            #endregion

            ISharedDictionary dic2 = SharedDictionary.Create(SharedDicTestContext.ServiceProvider);
            dic2[this, uid1, "key1"] = "value1";
            dic2[this, uid1, "key2"] = "value2";

            Assert.That(dic2[this, uid2, "key1"], Is.Null);
            Assert.That(dic2[this, uid2, "key2"], Is.Null);

            dic2.Ensure(uid2);

            SharedDictionaryImpl implDic2 = (SharedDictionaryImpl)dic2;
            implDic2.ImportFragments(dicFrag.Fragments, MergeMode.None);
            Assert.That(implDic2.GetSkippedFragments(this) == null);

            Assert.That(dic2[this, uid2, "key1"], Is.EqualTo("value1"));
            Assert.That(dic2[this, uid2, "key2"], Is.EqualTo("value2"));
        }
Esempio n. 15
0
        private TabInfo(SharedDictionary <string, string> localizedTabNameDictionary, SharedDictionary <string, string> fullUrlDictionary)
        {
            _localizedTabNameDictionary = localizedTabNameDictionary;
            _fullUrlDictionary          = fullUrlDictionary;

            PortalID            = Null.NullInteger;
            _authorizedRoles    = Null.NullString;
            ParentId            = Null.NullInteger;
            IconFile            = Null.NullString;
            IconFileLarge       = Null.NullString;
            _administratorRoles = Null.NullString;
            Title           = Null.NullString;
            Description     = Null.NullString;
            KeyWords        = Null.NullString;
            Url             = Null.NullString;
            SkinSrc         = Null.NullString;
            _skinDoctype    = Null.NullString;
            ContainerSrc    = Null.NullString;
            TabPath         = Null.NullString;
            StartDate       = Null.NullDate;
            EndDate         = Null.NullDate;
            RefreshInterval = Null.NullInteger;
            PageHeadText    = Null.NullString;
            SiteMapPriority = 0.5F;

            //UniqueId, Version Guid, and Localized Version Guid should be initialised to a new value
            UniqueId             = Guid.NewGuid();
            VersionGuid          = Guid.NewGuid();
            LocalizedVersionGuid = Guid.NewGuid();

            //Default Language Guid should be initialised to a null Guid
            DefaultLanguageGuid = Null.NullGuid;

            IsVisible        = true;
            HasBeenPublished = true;
            DisableLink      = false;

            Panes = new ArrayList();

            IsSystem = false;
        }
Esempio n. 16
0
        public static ISharedDictionary Read(string testName, string path, object o, Action <ISharedDictionary> beforeRead, out IList <ReadElementObjectInfo> errors)
        {
            ISharedDictionary dicRead = SharedDictionary.Create(ServiceProvider);

            if (beforeRead != null)
            {
                beforeRead(dicRead);
            }
            using (Stream str = new FileStream(path, FileMode.Open))
            {
                using (IStructuredReader sr = SimpleStructuredReader.CreateReader(str, ServiceProvider))
                {
                    using (ISharedDictionaryReader r = dicRead.RegisterReader(sr, MergeMode.None))
                    {
                        r.ReadPluginsDataElement(testName, o);
                        errors = r.ErrorCollector;
                    }
                }
            }
            return(dicRead);
        }
Esempio n. 17
0
        private Context(bool proxified)
        {
            _serviceContainer = new ContextServiceContainer(this);
            _dic           = SharedDictionary.Create(_serviceContainer);
            _configManager = ConfigurationManager.Create(_dic);
            _reqLayer      = new RequirementLayer("Context");

            _pluginRunner = new PluginRunner(_serviceContainer, _configManager.ConfigManager);
            _serviceContainer.Add(RequirementLayerSerializer.Instance);
            _serviceContainer.Add(SimpleTypeFinder.Default);

            if (proxified)
            {
                _proxifiedContext = (IContext)_pluginRunner.ServiceHost.InjectExternalService(typeof(IContext), this);
            }
            else
            {
                _proxifiedContext = this;
                _serviceContainer.Add <IContext>(this);
            }
            _pluginRunner.Initialize(_proxifiedContext);
        }
Esempio n. 18
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;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        public void TestDictionaryCount()
        {
            var runtime    = PSharpRuntime.Create();
            var dictionary = SharedDictionary.Create <int, string>(runtime);
            var counter    = SharedCounter.Create(runtime);
            var tcs1       = new TaskCompletionSource <bool>();
            var tcs2       = new TaskCompletionSource <bool>();
            var failed     = false;

            runtime.OnFailure += delegate
            {
                failed = true;
                tcs1.TrySetResult(true);
                tcs2.TrySetResult(true);
            };

            var m1 = runtime.CreateMachine(typeof(M), new E(dictionary, counter, tcs1));
            var m2 = runtime.CreateMachine(typeof(N), new E(dictionary, counter, tcs2));

            Task.WaitAll(tcs1.Task, tcs2.Task);
            Assert.False(failed);
            Assert.True(counter.GetValue() == T);
        }
Esempio n. 20
0
        public void TestProductionSharedObjects()
        {
            var runtime    = RuntimeFactory.Create();
            var dictionary = SharedDictionary.Create <int, string>(runtime);
            var counter    = SharedCounter.Create(runtime);
            var tcs1       = new TaskCompletionSource <bool>();
            var tcs2       = new TaskCompletionSource <bool>();
            var failed     = false;

            runtime.OnFailure += (ex) =>
            {
                failed = true;
                tcs1.TrySetResult(true);
                tcs2.TrySetResult(true);
            };

            var m1 = runtime.CreateActor(typeof(M), new E(dictionary, counter, tcs1));
            var m2 = runtime.CreateActor(typeof(N), new E(dictionary, counter, tcs2));

            Task.WaitAll(tcs1.Task, tcs2.Task);
            Assert.False(failed);
            Assert.True(counter.GetValue() is 100);
        }
Esempio n. 21
0
        private async void showCount()
        {
            // if you generate code for Xamarin.iOS, you use under.

            /*Utf8Json.Resolvers.CompositeResolver.Register(
             *  // code generating resolver
             *  Utf8Json.Resolvers.GeneratedResolver.Instance,
             *  Utf8Json.Resolvers.BuiltinResolver.Instance,
             *  Utf8Json.Resolvers.AttributeFormatterResolver.Instance,
             *  Utf8Json.Resolvers.DynamicGenericResolver.Instance,
             *  Utf8Json.Resolvers.EnumResolver.Default
             * );*/
            // var formatterResolver = new Utf8JsonFormatterResolver(Utf8Json.Resolvers.CompositeResolver.Instance);

            var formatterResolver = new Utf8JsonFormatterResolver(AotStandardResolver.Default);
            var sharedDictionary  = new SharedDictionary(
                new Utf8JsonSerializer(formatterResolver),
                IsolatedFileStorage.Default,
                AesCryptoConverter.Default
                );
            await sharedDictionary.LoadFromStorageAsync();

            if (sharedDictionary.TryGetProperty(welcomeKey, out int count))
            {
                WelcomeCounter.Text = $"Welcome Count: {count}";
            }
            else
            {
                WelcomeCounter.Text = $"First Welcome!";
            }

            count++;

            sharedDictionary.SetProperty(welcomeKey, count);

            await sharedDictionary.SaveToStorageAsync();
        }
Esempio n. 22
0
        public static async Task Main(string[] args)
        {
            var sharedDictionary = new SharedDictionary(Utf8JsonSerializer.Default, FileStorage.Default, null);

            sharedDictionary.SetProperty("text", "sssss");
            sharedDictionary.SetProperty("number", 1234);
            sharedDictionary.SetProperty("data", new Data());
            sharedDictionary.SetProperty("list", new List <int> {
                1, 2, 3, 4
            });

            await sharedDictionary.SaveToStorageAsync();

            sharedDictionary = new SharedDictionary(Utf8JsonSerializer.Default, FileStorage.Default, null);
            await sharedDictionary.LoadFromStorageAsync();

            foreach (var property in sharedDictionary)
            {
                WriteLine($"key: {property.Key}");
            }

            WriteLine(sharedDictionary.GetProperty <string>("text"));
            WriteLine(sharedDictionary.GetProperty <int>("number"));
            WriteLine(sharedDictionary.GetProperty <long>("number"));
            WriteLine(sharedDictionary.GetProperty <Data>("data"));
            WriteLine(sharedDictionary.GetProperty <List <int> >("list")?.Count);
            WriteLine(sharedDictionary.GetProperty <IEnumerable <int> >("list").Count());

            var serializer = new Utf8JsonSerializer();

            serializer.MigrationTypeDictionary[TypeCache <Data> .FullName] = TypeCache <MigratedData> .FullName;
            sharedDictionary = new SharedDictionary(serializer, FileStorage.Default, null);
            await sharedDictionary.LoadFromStorageAsync();

            WriteLine($"MigratedData: {sharedDictionary.GetProperty<MigratedData>("data")}");
        }
Esempio n. 23
0
        private TabInfo(SharedDictionary<string, string> localizedTabNameDictionary, SharedDictionary<string, string> fullUrlDictionary)
        {
            _localizedTabNameDictionary = localizedTabNameDictionary;
            _fullUrlDictionary = fullUrlDictionary;

            PortalID = Null.NullInteger;
            _authorizedRoles = Null.NullString;
            ParentId = Null.NullInteger;
            IconFile = Null.NullString;
            IconFileLarge = Null.NullString;
            _administratorRoles = Null.NullString;
            Title = Null.NullString;
            Description = Null.NullString;
            KeyWords = Null.NullString;
            Url = Null.NullString;
            SkinSrc = Null.NullString;
            _skinDoctype = Null.NullString;
            ContainerSrc = Null.NullString;
            TabPath = Null.NullString;
            StartDate = Null.NullDate;
            EndDate = Null.NullDate;
            RefreshInterval = Null.NullInteger;
            PageHeadText = Null.NullString;
            SiteMapPriority = 0.5F;

            //UniqueId, Version Guid, and Localized Version Guid should be initialised to a new value
            UniqueId = Guid.NewGuid();
            VersionGuid = Guid.NewGuid();
            LocalizedVersionGuid = Guid.NewGuid();

            //Default Language Guid should be initialised to a null Guid
            DefaultLanguageGuid = Null.NullGuid;

            IsVisible = true;
            DisableLink = false;
        }
Esempio n. 24
0
        /// <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;
        }
Esempio n. 25
0
 internal static void StorePortalAliasesInCache(SharedDictionary<string, PortalAliasInfo> aliases, FriendlyUrlSettings settings)
 {
     SetPortalCache(PortalAliasListKey, aliases, settings);
 }
Esempio n. 26
0
 private static void AddStandardPagesToDict(SharedDictionary<string, string> tabIndex,
                                             Dictionary<string, DupKeyCheck> dupCheck,
                                             string httpAlias,
                                             int portalId,
                                             string cultureCode)
 {
     int tabDepth = 0; //we ignore tab depth as it is only one for these in-built urls
     //850 : add in the culture code to the redirect if supplied
     string portalRewritePath = "?PortalId=" + portalId.ToString();
     string cultureRewritePath = "";
     if (!string.IsNullOrEmpty(cultureCode))
     {
         cultureRewritePath += "&language=" + cultureCode;
     }
     //hard coded page paths - using 'tabDeleted' in case there is a clash with an existing page (ie, someone has created a page that takes place of the standard page, created page has preference)
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     "login",
                     portalRewritePath + "&ctl=Login" + cultureRewritePath,
                     -1,
                     UrlEnums.TabKeyPreference.TabDeleted,
                     ref tabDepth,
                     false,
                     false);
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     "register",
                     portalRewritePath + "&ctl=Register" + cultureRewritePath,
                     -1,
                     UrlEnums.TabKeyPreference.TabDeleted,
                     ref tabDepth,
                     false,
                     false);
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     "terms",
                     portalRewritePath + "&ctl=Terms" + cultureRewritePath,
                     -1,
                     UrlEnums.TabKeyPreference.TabDeleted,
                     ref tabDepth,
                     false,
                     false);
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     "privacy",
                     portalRewritePath + "&ctl=Privacy" + cultureRewritePath,
                     -1,
                     UrlEnums.TabKeyPreference.TabDeleted,
                     ref tabDepth,
                     false,
                     false);
 }
Esempio n. 27
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;
        }
        /// <summary>
        /// returns a tabId indexed dictionary of Friendly Urls
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="forceRebuild"></param>
        /// <param name="bypassCache"></param>
        /// <param name="settings"></param>
        /// <param name="customAliasForTabs"></param>
        /// <param name="parentTraceId"></param>
        /// <returns></returns>
        internal static SharedDictionary<int, SharedDictionary<string, string>> FetchCustomUrlDictionary(int portalId, 
                                    bool forceRebuild, 
                                    bool bypassCache, 
                                    FriendlyUrlSettings settings,
                                    out SharedDictionary<string, string> customAliasForTabs, 
                                    Guid parentTraceId)
        {
            SharedDictionary<int, SharedDictionary<string, string>> urlDict;
            //this contains a list of all tabs for all the portals that have been retrieved
            List<int> urlPortals; //this contains a list of the portals that have been retrieved
            //get the objects from the cache
            var cc = new CacheController();
            cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs);

            if (urlDict != null && forceRebuild == false && bypassCache == false)
            {
                if (urlPortals == null)
                //no portals retrieved from cache, but was a dictionary.  Bit weird, but we'll run with it
                {
                    urlPortals = new List<int>();
                }

                //check to see if this portal has been included in the dict
                if (urlPortals.Contains(portalId) == false)
                {
                    //ok, there is a url dictionary, but this portal isn't in it, so 
                    //put it in and get the urls for this portal
                    //this call appends extra portals to the list
                    urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs);
                    urlPortals.Add(portalId);

                    cc.StoreFriendlyUrlIndexInCache(urlDict,
                                                urlPortals,
                                                customAliasForTabs, settings,
                                                "Portal Id " + portalId.ToString() + " added to index.");
                }
            }
            else //either values are null (Not in cache) or we want to force the rebuild, or we want to bypass the cache
            {
                //rebuild the dictionary for this portal
                urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs);
                urlPortals = new List<int> { portalId }; //always rebuild the portal list
                if (bypassCache == false) //if we are to cache this item (byPassCache = false)
                {
                    //cache these items
                    string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache";
                    cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason);
                }
            }
            return urlDict;
        }
Esempio n. 29
0
        private static object GetResourceFileCallBack(CacheItemArgs cacheItemArgs)
        {
            string cacheKey = cacheItemArgs.CacheKey;
            Dictionary <string, string> resources = null;

            string filePath = null;

            try
            {
                //Get resource file lookup to determine if the resource file even exists
                SharedDictionary <string, bool> resourceFileExistsLookup = GetResourceFileLookupDictionary();

                if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey))
                {
                    //check if an absolute reference for the resource file was used
                    if (cacheKey.Contains(":\\") && Path.IsPathRooted(cacheKey))
                    {
                        //if an absolute reference, check that the file exists
                        if (File.Exists(cacheKey))
                        {
                            filePath = cacheKey;
                        }
                    }

                    //no filepath found from an absolute reference, try and map the path to get the file path
                    if (filePath == null)
                    {
                        filePath = HostingEnvironment.MapPath(Globals.ApplicationPath + cacheKey);
                    }

                    //The file is not in the lookup, or we know it exists as we have found it before
                    if (File.Exists(filePath))
                    {
                        if (filePath != null)
                        {
                            var doc = new XPathDocument(filePath);
                            resources = new Dictionary <string, string>();
                            foreach (XPathNavigator nav in doc.CreateNavigator().Select("root/data"))
                            {
                                if (nav.NodeType != XPathNodeType.Comment)
                                {
                                    var selectSingleNode = nav.SelectSingleNode("value");
                                    if (selectSingleNode != null)
                                    {
                                        resources[nav.GetAttribute("name", String.Empty)] = selectSingleNode.Value;
                                    }
                                }
                            }
                        }
                        cacheItemArgs.CacheDependency = new DNNCacheDependency(filePath);

                        //File exists so add it to lookup with value true, so we are safe to try again
                        using (resourceFileExistsLookup.GetWriteLock())
                        {
                            resourceFileExistsLookup[cacheKey] = true;
                        }
                    }
                    else
                    {
                        //File does not exist so add it to lookup with value false, so we don't try again
                        using (resourceFileExistsLookup.GetWriteLock())
                        {
                            resourceFileExistsLookup[cacheKey] = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("The following resource file caused an error while reading: {0}", filePath), ex);
            }
            return(resources);
        }
Esempio n. 30
0
 public E(SharedDictionary <int, string> dictionary, SharedCounter counter, TaskCompletionSource <bool> tcs)
 {
     this.Dictionary = dictionary;
     this.Counter    = counter;
     this.Tcs        = tcs;
 }
Esempio n. 31
0
        /// <summary>
        /// returns a tabId indexed dictionary of Friendly Urls
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="forceRebuild"></param>
        /// <param name="bypassCache"></param>
        /// <param name="settings"></param>
        /// <param name="customAliasForTabs"></param>
        /// <param name="parentTraceId"></param>
        /// <returns></returns>
        internal static SharedDictionary <int, SharedDictionary <string, string> > FetchCustomUrlDictionary(int portalId,
                                                                                                            bool forceRebuild,
                                                                                                            bool bypassCache,
                                                                                                            FriendlyUrlSettings settings,
                                                                                                            out SharedDictionary <string, string> customAliasForTabs,
                                                                                                            Guid parentTraceId)
        {
            SharedDictionary <int, SharedDictionary <string, string> > urlDict;
            //this contains a list of all tabs for all the portals that have been retrieved
            ConcurrentBag <int> urlPortals; //this contains a list of the portals that have been retrieved
            //get the objects from the cache
            var cc = new CacheController();

            cc.GetFriendlyUrlIndexFromCache(out urlDict, out urlPortals, out customAliasForTabs);

            if (urlDict != null && forceRebuild == false && bypassCache == false)
            {
                if (urlPortals == null)
                //no portals retrieved from cache, but was a dictionary.  Bit weird, but we'll run with it
                {
                    urlPortals = new ConcurrentBag <int>();
                }

                //check to see if this portal has been included in the dict
                if (urlPortals.Contains(portalId) == false)
                {
                    //ok, there is a url dictionary, but this portal isn't in it, so
                    //put it in and get the urls for this portal
                    //this call appends extra portals to the list
                    urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs);
                    urlPortals.Add(portalId);

                    cc.StoreFriendlyUrlIndexInCache(urlDict,
                                                    urlPortals,
                                                    customAliasForTabs, settings,
                                                    "Portal Id " + portalId.ToString() + " added to index.");
                }
            }
            else //either values are null (Not in cache) or we want to force the rebuild, or we want to bypass the cache
            {
                //rebuild the dictionary for this portal
                urlDict    = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs);
                urlPortals = new ConcurrentBag <int> {
                    portalId
                };                        //always rebuild the portal list
                if (bypassCache == false) //if we are to cache this item (byPassCache = false)
                {
                    //cache these items
                    string reason = forceRebuild ? "Force Rebuild of Index" : "Index not in cache";
                    cc.StoreFriendlyUrlIndexInCache(urlDict, urlPortals, customAliasForTabs, settings, reason);
                }
            }
            return(urlDict);
        }
 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 void AddStandardPagesToDict(SharedDictionary<string, string> tabIndex,
                                                    Dictionary<string, DupKeyCheck> dupCheck,
                                                    string httpAlias,
                                                    int portalId,
                                                    string cultureCode)
        {
            int tabDepth = 0; //we ignore tab depth as it is only one for these in-built urls
            //850 : add in the culture code to the redirect if supplied
            string portalRewritePath = "?PortalId=" + portalId.ToString();
            string cultureRewritePath = "";
            if (!string.IsNullOrEmpty(cultureCode))
            {
                cultureRewritePath += "&language=" + cultureCode;
            }
            //hard coded page paths - using 'tabDeleted' in case there is a clash with an existing page (ie, someone has created a page that takes place of the standard page, created page has preference)
            
            //need check custom login/register page set in portal and redirect to the specific page.
            var portal = PortalController.Instance.GetPortal(portalId);
            var loginRewritePath = portalRewritePath + "&ctl=Login" + cultureRewritePath;
            var loginPreference = UrlEnums.TabKeyPreference.TabDeleted;
            var loginTabId = Null.NullInteger;
            if (portal != null && portal.LoginTabId > Null.NullInteger && Globals.ValidateLoginTabID(portal.LoginTabId))
            {
                loginTabId = portal.LoginTabId;
                loginPreference = UrlEnums.TabKeyPreference.TabOK;
                loginRewritePath = CreateRewritePath(loginTabId, cultureCode);
            }
            AddToTabDict(tabIndex,
                            dupCheck,
                            httpAlias,
                            "login",
                            loginRewritePath,
                            loginTabId,
                            loginPreference,
                            ref tabDepth,
                            false,
                            false);

            var registerRewritePath = portalRewritePath + "&ctl=Register" + cultureRewritePath;
            var registerPreference = UrlEnums.TabKeyPreference.TabDeleted;
            var registerTabId = Null.NullInteger;
            if (portal != null && portal.RegisterTabId > Null.NullInteger)
            {
                registerTabId = portal.RegisterTabId;
                registerPreference = UrlEnums.TabKeyPreference.TabOK;
                registerRewritePath = CreateRewritePath(registerTabId, cultureCode);
            }
            AddToTabDict(tabIndex,
                            dupCheck,
                            httpAlias,
                            "register",
                            registerRewritePath,
                            registerTabId,
                            registerPreference,
                            ref tabDepth,
                            false,
                            false);
            AddToTabDict(tabIndex,
                            dupCheck,
                            httpAlias,
                            "terms",
                            portalRewritePath + "&ctl=Terms" + cultureRewritePath,
                            -1,
                            UrlEnums.TabKeyPreference.TabDeleted,
                            ref tabDepth,
                            false,
                            false);
            AddToTabDict(tabIndex,
                            dupCheck,
                            httpAlias,
                            "privacy",
                            portalRewritePath + "&ctl=Privacy" + cultureRewritePath,
                            -1,
                            UrlEnums.TabKeyPreference.TabDeleted,
                            ref tabDepth,
                            false,
                            false);
        }
Esempio n. 34
0
        static void ResetCallHits(SharedDictionary<FunctionCall> callMap)
        {
            foreach (var call in callMap)
            {
                if (call == null || call.Hit <= 0)
                    continue;

                call.Hit--;

                //call.DashOffset -= FunctionCall.DashSize;
                //if (call.DashOffset < 0)
                //    call.DashOffset = FunctionCall.DashSpace;
            }
        }
Esempio n. 35
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;
        }
Esempio n. 36
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;
 }
Esempio n. 37
0
        /// <summary>
        /// Store the Url Dictionary (all tab urls / tabids) for the installation
        /// </summary>
        /// <param name="urlDict"></param>
        /// <param name="urlPortals"></param>
        /// <param name="customAliasTabs"></param>
        /// <param name="settings"></param>
        /// <param name="reason"></param>
        /// <remarks>
        /// </remarks>
        internal void StoreFriendlyUrlIndexInCache(SharedDictionary<int, SharedDictionary<string, string>> urlDict,
                                                List<int> urlPortals,
                                                SharedDictionary<string, string> customAliasTabs,
                                                FriendlyUrlSettings settings,
                                                string reason)
        {
            if (settings.LogCacheMessages)
            {
                onRemovePageIndex = RemovedPageIndexCallBack;
            }
            else
            {
                onRemovePageIndex = null;
            }

            LogRemovedReason = settings.LogCacheMessages;

            SetPageCache(UrlDictKey, urlDict, new DNNCacheDependency(GetTabsCacheDependency(urlPortals)), settings, onRemovePageIndex);

            SetPageCache(UrlPortalsKey, urlPortals, settings);
            SetPageCache(CustomAliasTabsKey, customAliasTabs, settings);

            if (settings.LogCacheMessages)
            {
                var elc = new EventLogController();

                var logValue = new LogInfo { LogTypeKey = "HOST_ALERT" };
                logValue.AddProperty("Url Rewriting Caching Message", "Friendly Url Index built and Stored in Cache.");
                logValue.AddProperty("Build Reason", reason);
                logValue.AddProperty("Cache Key", UrlDictKey);
                using (urlDict.GetReadLock())
                {
                    logValue.AddProperty("Item Count", urlDict.Values.Count.ToString());
                }
                logValue.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                logValue.AddProperty("Item added to cache", "Url Portals object added to cache.  Key:" + UrlPortalsKey + "  Items: " + urlPortals.Count.ToString());
                logValue.AddProperty("Item added to cache", "Custom Alias Tabs added to cache.  Key:" + CustomAliasTabsKey + " Items: " + customAliasTabs.Count.ToString());
                elc.AddLog(logValue);
            }
        }
Esempio n. 38
0
        void TimeoutFunctinCalls(SharedDictionary<FunctionCall> callMap)
        {
            foreach (FunctionCall call in callMap)
            {
                if (call == null || call.Hit <= 0)
                    continue;

                call.Hit--;

                call.DashOffset -= FunctionCall.DashSize;
                if (call.DashOffset < 0)
                    call.DashOffset = FunctionCall.DashSpace;
            }
        }
Esempio n. 39
0
        internal void AddFunctionCall(ref SharedDictionary<FunctionCall> map, int nodeId, FunctionCall call)
        {
            if (map == null)
                map = new SharedDictionary<FunctionCall>(1);

            if (!map.Contains(nodeId))
                map.Add(nodeId, call);
        }
        private void SetUrlInCache(string cacheKey, string url)
        {
            if (string.IsNullOrEmpty(cacheKey))
            {
                return;
            }

            var cachedUrls = DataCache.GetCache<SharedDictionary<string, string>>(UrlsCacheKey);

            if (cachedUrls == null)
            {
                cachedUrls = new SharedDictionary<string, string>();
            }
            using (cachedUrls.GetWriteLock())
            {
                cachedUrls[cacheKey] = url;
            }

            DataCache.SetCache(UrlsCacheKey, cachedUrls, TimeSpan.FromMinutes(UrlsCacheTimeout));
        }
Esempio n. 41
0
 internal void StoreTabPathsInCache(int portalId, SharedDictionary<string, string> tabPathDictionary, FriendlyUrlSettings settings)
 {
     SetPageCache(string.Format(TabPathsKey, portalId), 
                 tabPathDictionary, 
                 new DNNCacheDependency(GetTabsCacheDependency(new List<int> { portalId })), 
                 settings, 
                 null);
 }
        /// <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);
        }
Esempio n. 43
0
        private static bool TryGetFromResourceFile(string key, string resourceFile, int portalID, CustomizedLocale resourceType, ref string resourceValue)
        {
            bool   bFound           = Null.NullBoolean;
            string resourceFileName = resourceFile;

            switch (resourceType)
            {
            case CustomizedLocale.Host:
                resourceFileName = resourceFile.Replace(".resx", ".Host.resx");
                break;

            case CustomizedLocale.Portal:
                resourceFileName = resourceFile.Replace(".resx", ".Portal-" + portalID + ".resx");
                break;
            }

            if (resourceFileName.StartsWith("desktopmodules", StringComparison.InvariantCultureIgnoreCase) ||
                resourceFileName.StartsWith("admin", StringComparison.InvariantCultureIgnoreCase) ||
                resourceFileName.StartsWith("controls", StringComparison.InvariantCultureIgnoreCase))
            {
                resourceFileName = "~/" + resourceFileName;
            }

            //Local resource files are either named ~/... or <ApplicationPath>/...
            //The following logic creates a cachekey of /....
            string cacheKey = resourceFileName.Replace("~/", "/").ToLowerInvariant();

            if (!String.IsNullOrEmpty(Globals.ApplicationPath))
            {
                if (Globals.ApplicationPath != "/portals")
                {
                    if (cacheKey.StartsWith(Globals.ApplicationPath))
                    {
                        cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length);
                    }
                }
                else
                {
                    cacheKey = "~" + cacheKey;
                    if (cacheKey.StartsWith("~" + Globals.ApplicationPath))
                    {
                        cacheKey = cacheKey.Substring(Globals.ApplicationPath.Length + 1);
                    }
                }
            }

            //Get resource file lookup to determine if the resource file even exists
            SharedDictionary <string, bool> resourceFileExistsLookup = GetResourceFileLookupDictionary();

            if (ResourceFileMayExist(resourceFileExistsLookup, cacheKey))
            {
                //File is not in lookup or its value is true so we know it exists
                Dictionary <string, string> dicResources = GetResourceFile(cacheKey);
                if (dicResources != null)
                {
                    bFound = dicResources.TryGetValue(key, out resourceValue);
                }
            }

            return(bFound);
        }
Esempio n. 44
0
 private static void AddPermanentRedirectToDictionary(SharedDictionary<string, string> tabIndex,
                                                 Dictionary<string, DupKeyCheck> dupCheck,
                                                 string httpAlias,
                                                 TabInfo tab,
                                                 string tabPath,
                                                 ref string rewritePath,
                                                 ref int tabPathDepth,
                                                 bool checkForDupUrls,
                                                 bool isDeleted)
 {
     //because we have to catch all versions of this in the dictionary, then we have to add the 'base' url
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     tab.TabPath + "/tabid/" + tab.TabID + "/default",
                     rewritePath,
                     tab.TabID,
                     UrlEnums.TabKeyPreference.TabRedirected,
                     ref tabPathDepth,
                     checkForDupUrls,
                     isDeleted);
     //and put in the name-less one as well, just in case a prior version of the site was runnign without the tabnames (urlformat=sefriendly)
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     "/tabid/" + tab.TabID + "/default",
                     rewritePath,
                     tab.TabID,
                     UrlEnums.TabKeyPreference.TabRedirected,
                     ref tabPathDepth,
                     checkForDupUrls,
                     isDeleted);
     //finally, put one in for the ctl/tab combination, so that you can actually get to the page settings
     AddToTabDict(tabIndex,
                     dupCheck,
                     httpAlias,
                     tabPath.Replace("//", "/") + "/ctl/Tab",
                     CreateRewritePath(tab.TabID, "", "ctl=Tab"),
                     tab.TabID,
                     UrlEnums.TabKeyPreference.TabRedirected,
                     ref tabPathDepth,
                     checkForDupUrls,
                     isDeleted);
 }
        /// <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;
        }
        /// <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
                            PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId);
                            if (alias != null)
                            {
                                string customHttpAlias = alias.HTTPAlias;
                                url = customHttpAlias + "::" + url;
                            }
                        }
                        string cultureKey = redirect.CultureCode.ToLower();
                        var locales = LocaleController.Instance.GetLocales(portalId).Values;
                        if (String.IsNullOrEmpty(cultureKey))
                        {
                            //Add entry for each culture
                            foreach (Locale locale in locales)
                            {
                                AddEntryToDictionary(existingTabs, portalId, tab, locale.Code.ToLower(), url);
                            }
                        }
                        else
                        {
                            AddEntryToDictionary(existingTabs, portalId, tab, cultureKey, url);
                        }
                    }
                }
            }
            return existingTabs;
        }
    	private const int UserAgentsCacheTimeout = 60; //user agents cache expire time.(minutes)

        /// <summary>
        ///   Returns ClientCapability based on HttpRequest
        /// </summary>
        public override IClientCapability GetClientCapability(string userAgent)
        {
            DeviceInfoClientCapability deviceInfoClientCapability = null;

			if (!string.IsNullOrEmpty(userAgent))
			{
				bool found = false;

				//try to get content from cache
                var cachedUserAgents = DataCache.GetCache<SharedDictionary<string, DeviceInfoClientCapability>>(UserAgentsCacheKey);
				if (cachedUserAgents != null)
                {
                    using (cachedUserAgents.GetReadLock())
                    {
                        if (cachedUserAgents.ContainsKey(userAgent))
                        {
                            deviceInfoClientCapability = cachedUserAgents[userAgent];
                            found = true;
                        }                        
                    }
                }

				if (!found)
				{
					var deviceInfo = WurflProvider.GetDeviceInfo(userAgent);
					if (deviceInfo != null)
					{
						deviceInfoClientCapability = new DeviceInfoClientCapability(deviceInfo);

						//update cache content
						if(cachedUserAgents == null)
						{
                            cachedUserAgents = new SharedDictionary<string, DeviceInfoClientCapability>();
						}
                        using (cachedUserAgents.GetWriteLock())
                        {
                            cachedUserAgents[userAgent] = deviceInfoClientCapability;
                        }
					    DataCache.SetCache(UserAgentsCacheKey, cachedUserAgents, TimeSpan.FromMinutes(UserAgentsCacheTimeout));
					}
				}
			}

        	var wurflClientCapability =  new WURFLClientCapability(deviceInfoClientCapability);
            wurflClientCapability.UserAgent = userAgent;
            return wurflClientCapability;
        }
Esempio n. 48
0
 /// <summary>
 /// Retrieve the Url Dictionary for the installation.
 /// </summary>
 /// <param name="urlDict"></param>
 /// <param name="urlPortals"></param>
 /// <param name="customAliasTabs"></param>
 /// <remarks>
 /// </remarks>
 internal void GetFriendlyUrlIndexFromCache(out SharedDictionary<int, SharedDictionary<string, string>> urlDict,
                                            out List<int> urlPortals,
                                            out SharedDictionary<string, string> customAliasTabs)
 {
     urlDict = null;
     urlPortals = null;
     customAliasTabs = null;
     object rawDict = DataCache.GetCache(UrlDictKey); //contains a dictionary of tabs for all portals
     object rawPortals = DataCache.GetCache(UrlPortalsKey);
     //contas a list of portals for which we have retrieved the tabs
     object rawCustomAliasTabs = DataCache.GetCache(CustomAliasTabsKey);
     //contains a dictionary of tabs with custom aliases, for all portals
     if (rawDict != null)
     {
         urlDict = (SharedDictionary<int, SharedDictionary<string, string>>)rawDict;
     }
     if (rawPortals != null)
     {
         urlPortals = (List<int>)rawPortals;
     }
     if (rawCustomAliasTabs != null)
     {
         customAliasTabs = (SharedDictionary<string, string>)rawCustomAliasTabs;
     }
 }
Esempio n. 49
0
        /// <summary> 
        /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one 
        /// </summary>
        /// <param name="portalId"></param>
        /// <param name="minTabPathDepth">ByRef parameter to return the minimum tab path depth (the number of '/' in the tab path)</param> 
        /// <param name="maxTabPathDepth">ByRef parameter to return the maximum tab path depth (the number of '/' in the tab path)</param> 
        /// <param name="minAliasPathDepth">ByRef parameter to return the minimum alias path depth (the number of '/' in the alias path</param> 
        /// <param name="maxAliasPathDepth">ByRef parameter to return the maximum alias path depth (the number of '/' in the alias path)</param>
        /// <param name="settings"></param>
        /// <param name="forceRebuild"></param>
        /// <param name="bypassCache"></param>
        /// <param name="parentTraceId"></param>
        /// <returns>Dictionary (string, string) of Tab paths in tab key, with the rewrite path as the value</returns> 
        /// <remarks>
        /// Changes
        /// Task 608 : Incrementally build tab dictionary instead of building entire dicitionary all at once
        /// Task 609 : If usePortalAlias is specified, only build dictionary with specific portal alias : ignore others
        /// Task 791 : allow for specification of true/false for using thread locking to prevent multiple rebuilds on threads
        /// </remarks> 
        internal static SharedDictionary<string, string> FetchTabDictionary(int portalId,
                                                                                out int minTabPathDepth,
                                                                                out int maxTabPathDepth,
                                                                                out int minAliasPathDepth,
                                                                                out int maxAliasPathDepth,
                                                                                FriendlyUrlSettings settings,
                                                                                bool forceRebuild,
                                                                                bool bypassCache,
                                                                                Guid parentTraceId)
        {
            SharedDictionary<int, PathSizes> portalDepths;
            SharedDictionary<string, string> dict;

            //place threadlock to prevent two threads getting a null object
            //check for the tab dictionary in the DataCache
            var cc = new CacheController();
            cc.GetPageIndexFromCache(out dict, out portalDepths, settings);

            string reason = "";
            if (dict == null)
            {
                reason += "No Page index in cache;";
            }
            if (forceRebuild)
            {
                reason += "Force Rebuild;";
            }
            if (bypassCache)
            {
                reason += "Bypass Cache;";
            }
            if (dict != null)
            {
                using (dict.GetReadLock())
                {
                    reason += "Existing Page Index=" + dict.Count.ToString() + " items;";
                }
            }

            Hashtable homePageSkins; //keeps a list of skins set per home page and culture
            SharedDictionary<string, string> portalTabPathDictionary;
            if (dict != null && portalDepths != null && forceRebuild == false && bypassCache == false)
            {
                PathSizes depthInfo;
                bool changed = false;
                using (portalDepths.GetWriteLock())
                {
                    if (!portalDepths.ContainsKey(portalId))
                    {
                        reason += "Portal " + portalId.ToString() + " added to index;";

                        //tab dictionary built, but portal not in it
                        dict = BuildTabDictionary(out depthInfo,
                                                    settings,
                                                    portalId,
                                                    dict,
                                                    out homePageSkins,
                                                    out portalTabPathDictionary,
                                                    parentTraceId);

                        //recheck portal add, when running with locks can get duplicate key exceptions
                        if (portalDepths.ContainsKey(portalId) == false)
                        {
                            portalDepths.Add(portalId, depthInfo);
                            changed = true;
                        }

                        cc.StoreTabPathsInCache(portalId, portalTabPathDictionary, settings);
                        CacheController.StoreHomePageSkinsInCache(portalId, homePageSkins);
                    }
                    else
                    {
                        depthInfo = portalDepths[portalId];
                    }
                }
                if (changed)
                {
                    //restash dictionary
                    cc.StorePageIndexInCache(dict, portalDepths, settings, reason);
                }

                if (depthInfo != null)
                {
                    minTabPathDepth = depthInfo.MinTabPathDepth;
                    maxTabPathDepth = depthInfo.MaxTabPathDepth;
                    minAliasPathDepth = depthInfo.MinAliasDepth;
                    maxAliasPathDepth = depthInfo.MaxAliasDepth;
                }
                else
                {
                    //fallback values, should never get here: mainly for compiler wranings
                    minTabPathDepth = 1;
                    maxTabPathDepth = 10;
                    minAliasPathDepth = 1;
                    maxAliasPathDepth = 4;
                }
            }
            else
            {
                //the cached dictionary was null or forceRebuild = true or bypassCache = true, so go get a new dictionary
                PathSizes depthInfo;
                dict = BuildTabDictionary(out depthInfo,
                                            settings,
                                            portalId,
                                            null,
                                            out homePageSkins,
                                            out portalTabPathDictionary,
                                            parentTraceId);

                //store the fact that this portal has been built
                portalDepths = new SharedDictionary<int, PathSizes>();
                using (portalDepths.GetWriteLock())
                {
                    portalDepths.Add(portalId, depthInfo);
                }
                if (bypassCache == false) //only cache if bypass not switched on
                {
                    cc.StorePageIndexInCache(dict, portalDepths, settings, reason);
                }
                cc.StoreTabPathsInCache(portalId, portalTabPathDictionary, settings);
                CacheController.StoreHomePageSkinsInCache(portalId, homePageSkins);
                minTabPathDepth = depthInfo.MinTabPathDepth;
                maxTabPathDepth = depthInfo.MaxTabPathDepth;
                minAliasPathDepth = depthInfo.MinAliasDepth;
                maxAliasPathDepth = depthInfo.MaxAliasDepth;
            }
            return dict;
        }
Esempio n. 50
0
        private static void AddCustomRedirectsToDictionary(SharedDictionary<string, string> tabIndex,
                                                    Dictionary<string, DupKeyCheck> dupCheck,
                                                    string httpAlias,
                                                    TabInfo tab,
                                                    FriendlyUrlSettings settings,
                                                    FriendlyUrlOptions options,
                                                    ref string rewritePath,
                                                    out int tabPathDepth,
                                                    ref List<string> customHttpAliasesUsed,
                                                    bool isDeleted,
                                                    Guid parentTraceId)
        {
            tabPathDepth = 1;
            var duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected;
            bool checkForDupUrls = settings.CheckForDuplicateUrls;
            //697 : custom url rewrites with large number of path depths fail because of incorrect path depth calculation
            int maxTabPathDepth = 1;
            string newRewritePath = rewritePath;
            string aliasCulture = null;
            //get the culture for this alias
            var primaryAliases = TestablePortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID).ToList();

            if (primaryAliases.Count > 0)
            {
                aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(tab.PortalID, httpAlias);
            }
            foreach (var redirect in tab.TabUrls)
            {
                //allow for additional qs parameters
                if (!String.IsNullOrEmpty(redirect.QueryString))
                {
                    rewritePath += (redirect.QueryString.StartsWith("&")) ? redirect.QueryString : "&" + redirect.QueryString;
                }

                string redirectTabPath = redirect.Url;
                string redirectedRewritePath = rewritePath;

                //770 : allow for custom portal aliases
                string redirectAlias = httpAlias;
                if (redirect.PortalAliasId > 0)
                {
                    //has a custom portal alias
                    var pac = new PortalAliasController();
                    PortalAliasInfo customAlias = pac.GetPortalAliasByPortalAliasID(redirect.PortalAliasId);
                    if (customAlias != null)
                    {
                        //this will be used to add the Url to the dictionary
                        redirectAlias = customAlias.HTTPAlias;
                        //add to the list of custom aliases used by the portal
                        if (customHttpAliasesUsed == null)
                        {
                            customHttpAliasesUsed = new List<string>();
                        }
                        if (!customHttpAliasesUsed.Contains(redirectAlias))
                        {
                            customHttpAliasesUsed.Add(redirectAlias);
                        }
                    }
                }
                //set the redirect status using the httpStatus
                switch (redirect.HttpStatus)
                {
                    case "301":
                        redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                        ActionType.Redirect301,
                                                                                        RedirectReason.Custom_Redirect);
                        break;
                    case "302":
                        redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                        ActionType.Redirect302,
                                                                                        RedirectReason.Custom_Redirect);
                        break;
                    case "404":
                        redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                        ActionType.Output404,
                                                                                        RedirectReason.Custom_Redirect);
                        break;
                    case "200":
                        //when there is a 200, then replace the 'standard' path
                        newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(newRewritePath,
                                                                                        ActionType.CheckFor301,
                                                                                        RedirectReason.Custom_Redirect);
                        //672 : replacement urls have preference over all redirects, deleted tabs and standard urls
                        duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabOK;
                        break;
                }
                //check the culture of the redirect to see if it either doesn't match the alias or needs to specify
                //the language when requested
                if (redirect.CultureCode != null)
                {
                    if (redirect.CultureCode != "" && redirect.CultureCode != "Default")
                    {
                        //806 : specify duplicates where the alias culture doesn't match the redirect culture
                        //so that redirect to the best match between alias culture and redirect culture
                        //compare the supplied alias culture with the redirect culture
                        //856 : if alias culture == "" and a custom 301 redirect then redirects are forced
                        if (!string.IsNullOrEmpty(aliasCulture) && aliasCulture != redirect.CultureCode)
                        {
                            //the culture code and the specific culture alias don't match
                            //set 301 check status and set to delete if a duplicate is found
                            redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(
                                                                                redirectedRewritePath,
                                                                                ActionType.CheckFor301,
                                                                                RedirectReason.Custom_Redirect);
                            newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(newRewritePath,
                                                                                ActionType.CheckFor301,
                                                                                RedirectReason.Custom_Redirect);
                            duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected;
                        }
                        //add on the culture code for the redirect, so that the rewrite silently sets the culture for the page
                        RewriteController.AddLanguageCodeToRewritePath(ref redirectedRewritePath, redirect.CultureCode);
                    }
                }
                //now add the custom redirect to the tab dictionary
                if (String.Compare(httpAlias, redirectAlias, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AddToTabDict(tabIndex,
                                    dupCheck,
                                    httpAlias,
                                    redirectTabPath,
                                    redirectedRewritePath,
                                    tab.TabID,
                                    duplicateHandlingPreference,
                                    ref tabPathDepth,
                                    checkForDupUrls,
                                    isDeleted);
                }
                else
                {
                    //770 : there is a specific alias for this tab
                    //if not a redirect already, make it a redirect for the wrong (original) rewrite path
                    string wrongAliasRedirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(redirectedRewritePath,
                                                                                                            ActionType.Redirect301,
                                                                                                            RedirectReason.Custom_Tab_Alias);
                    //add in the entry with the specific redirectAlias
                    if (redirectTabPath == "")
                    {
                        //when adding a blank custom Url, also add in a standard tab path url, because any url that also includes querystring data will use the standard tab path
                        string tabPath = GetTabPath(tab, options, parentTraceId);
                        string stdDictRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                                  ActionType.CheckFor301,
                                                                                                  RedirectReason.Custom_Tab_Alias);
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        redirectAlias,
                                        tabPath,
                                        stdDictRewritePath,
                                        tab.TabID,
                                        UrlEnums.TabKeyPreference.TabOK,
                                        ref tabPathDepth,
                                        checkForDupUrls,
                                        isDeleted);
                        //then add in the portal alias with no tabpath (ie like a site root url)
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        redirectAlias,
                                        redirectTabPath,
                                        redirectedRewritePath,
                                        tab.TabID,
                                        duplicateHandlingPreference,
                                        ref tabPathDepth,
                                        checkForDupUrls,
                                        isDeleted);
                        //838 : disabled tabs with custom aliases - still load the settings page without redirect
                        //disabled / not active by date / external url pages cannot navigate to settings page
                        if (tab.DisableLink || !string.IsNullOrEmpty(tab.Url) ||
                           (tab.EndDate < DateTime.Now && tab.EndDate > DateTime.MinValue) ||
                           (tab.StartDate > DateTime.Now && tab.StartDate > DateTime.MinValue))
                        {
                            string settingsUrl = tabPath + "/ctl/Tab";
                            string settingsRewritePath = CreateRewritePath(tab.TabID, redirect.CultureCode, "ctl=Tab");
                            //no redirect on the ctl/Tab url
                            //add in the ctl/tab Url for the custom alias, with no redirect so that the page settings can be loaded
                            AddToTabDict(tabIndex,
                                            dupCheck,
                                            redirectAlias,
                                            settingsUrl,
                                            settingsRewritePath,
                                            tab.TabID,
                                            UrlEnums.TabKeyPreference.TabRedirected,
                                            ref tabPathDepth,
                                            settings.CheckForDuplicateUrls,
                                            isDeleted);
                        }
                    }
                    else
                    {
                        //add in custom entry with different alias
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        redirectAlias,
                                        redirectTabPath,
                                        redirectedRewritePath,
                                        tab.TabID,
                                        duplicateHandlingPreference,
                                        ref tabPathDepth,
                                        checkForDupUrls,
                                        isDeleted);
                        //add in the entry with the original alias, plus an instruction to redirect if it's used
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        httpAlias,
                                        redirectTabPath,
                                        wrongAliasRedirectedRewritePath,
                                        tab.TabID,
                                        duplicateHandlingPreference,
                                        ref tabPathDepth,
                                        checkForDupUrls,
                                        isDeleted);
                    }
                }
                if (tabPathDepth > maxTabPathDepth)
                {
                    maxTabPathDepth = tabPathDepth;
                }
            }
            //return the highest tabpath depth found
            tabPathDepth = maxTabPathDepth;
            //return any changes to the rewritePath
            rewritePath = newRewritePath;
        }
Esempio n. 51
0
        private static void AddSiteRootRedirects(PathSizes pathSizes,
                                        SharedDictionary<string, string> tabIndex,
                                        IEnumerable<PortalAliasInfo> chosenAliases,
                                        bool hasSiteRootRedirect,
                                        Dictionary<string, DupKeyCheck> dupCheck,
                                        ICollection<string> usingHttpAliases)
        {
            foreach (PortalAliasInfo alias in chosenAliases) //and that is once per portal alias per portal
            {
                string httpAlias = alias.HTTPAlias;

                //check to see if there is a parameter rewrite rule that allows for parameters on the site root
                if (hasSiteRootRedirect)
                {
                    int tempPathDepth = 0;
                    AddToTabDict(tabIndex,
                                 dupCheck,
                                 httpAlias,
                                 "*",
                                 "",
                                 -1,
                                 UrlEnums.TabKeyPreference.TabOK,
                                 ref tempPathDepth,
                                 false,
                                 false);
                }

                pathSizes.SetAliasDepth(httpAlias);

                //keep track of the http Aliases, this will be used to feed into the tab dictionary (ie, one alias per tab)
                usingHttpAliases.Add(httpAlias.ToLowerInvariant());
            }
        }
Esempio n. 52
0
        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;
        }
Esempio n. 53
0
        private static int AddTabToTabDict(SharedDictionary<string, string> tabIndex,
                                                Dictionary<string, DupKeyCheck> dupCheck,
                                                string httpAlias,
                                                string aliasCulture,
                                                string customHttpAlias,
                                                PortalInfo thisPortal,
                                                string tabPath,
                                                ref List<string> customAliasesUsed,
                                                TabInfo tab,
                                                FriendlyUrlSettings settings,
                                                FriendlyUrlOptions options,
                                                int homeTabId,
                                                ref Hashtable homePageSkins,
                                                Guid parentTraceId)
        {
            string rewritePath = "";
            int tabPathDepth = 0;
            bool customAliasUsedAndNotCurrent = !String.IsNullOrEmpty(customHttpAlias) && customHttpAlias != httpAlias;

            //592 : check the permanent redirect value
            //736 : 5.5 changes : track tab culture code
            string cultureCode = tab.CultureCode;
            if (String.IsNullOrEmpty(cultureCode))
            {
                cultureCode = aliasCulture;
            }
            bool permanentRedirect = tab.PermanentRedirect;
            //determine the rewrite parameter
            //for deleted, expired or pages not enabled yet, direct to the home page if the setting is enabled
            //534 : tab is disabled, mark as deleted (don't want to cause duplicate tab warnings)
            bool isDeleted = (tab.IsDeleted || tab.DisableLink ||
                             (tab.EndDate < DateTime.Now && tab.EndDate > DateTime.MinValue) ||
                             (tab.StartDate > DateTime.Now && tab.StartDate > DateTime.MinValue));
            if (isDeleted)
            // don't care what setting is, redirect code will decide whether to redirect or 404 - just mark as page deleted && 
            // settings.DeletedTabHandlingValue == DeletedTabHandlingTypes.Do301RedirectToPortalHome)
            {
                //777: force 404 result for all deleted pages instead of relying on 'not found'
                //838 : separate handling for disabled pages
                ActionType action = settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error
                                    ? ActionType.Output404
                                    : ActionType.Redirect301;
                rewritePath = tab.DisableLink
                                  ? CreateRewritePath(homeTabId, cultureCode, action, RedirectReason.Disabled_Page)
                                  : CreateRewritePath(homeTabId, cultureCode, action, RedirectReason.Deleted_Page);
            }
            else
            {
                //for all other pages, rewrite to the correct tabId for that page
                //592 : new permanentRedirect value
                if (permanentRedirect)
                {
                    rewritePath = CreateRewritePath(tab.TabID,
                                                    cultureCode,
                                                    ActionType.Redirect301,
                                                    RedirectReason.Tab_Permanent_Redirect);
                }
                else
                {
                    //852 : skin per alias at tab level - if specified
                    if (tab.AliasSkins != null && tab.AliasSkins.ContainsAlias(httpAlias))
                    {
                        TabAliasSkinInfo tas = tab.AliasSkins.FindByHttpAlias(httpAlias);
                        if (tas != null)
                        {
                            string skinSrc = tas.SkinSrc;
                            if (!string.IsNullOrEmpty(skinSrc))
                            {
                                //add skin src into rewrite path
                                rewritePath = CreateRewritePath(tab.TabID, cultureCode, "skinSrc=" + skinSrc);
                            }

                            //now add to the home page skin hashtable if it's the home page.
                            if (homeTabId == tab.TabID)
                            {
                                string key = httpAlias + "::" + cultureCode;
                                string key2 = httpAlias;
                                if (homePageSkins.ContainsKey(key) == false)
                                {
                                    homePageSkins.Add(key, skinSrc);
                                }
                                if (homePageSkins.ContainsKey(key2) == false)
                                {
                                    homePageSkins.Add(key2, skinSrc);
                                }
                            }
                        }
                    }
                    else
                    {
                        rewritePath = CreateRewritePath(tab.TabID, cultureCode);
                    }
                }

                if (thisPortal != null && (thisPortal.UserTabId == tab.TabID || thisPortal.UserTabId == tab.ParentId || thisPortal.UserTabId == -1))
                {
                    //user profile action specified.  If tabid match for this tab, add a do301 check because we want to make
                    //sure that the trimmed Url is used when appropriate
                    rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                ActionType.CheckFor301,
                                                                                RedirectReason.User_Profile_Url);
                }
            }

            if (tabPath.Replace("//", "/") != tab.TabPath.Replace("//", "/"))
            {
                //when the generated tab path is different to the standard tab path, character substituion has happened
                //this entry is going to have space substitution in it, so it is added into the dictionary with a delete notification and a 301 replaced 
                //this entry is the 'original' (spaces removed) version ie mypage
                string substituteRewritePath = rewritePath;
                if (!isDeleted)
                //if it is deleted, we don't care if the spaces were replaced, or anything else, just take care in deleted handling
                {
                    string replaceSpaceWith = String.Empty;
                    if (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing)
                    {
                        replaceSpaceWith = settings.ReplaceSpaceWith;
                    }
                    substituteRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(substituteRewritePath,
                                                            ActionType.Redirect301,
                                                            tabPath.Contains(replaceSpaceWith)
                                                                ? RedirectReason.Spaces_Replaced
                                                                : RedirectReason.Custom_Redirect);
                }
                //the preference variable determines what to do if a duplicate tab is found already in the dictionary
                var preference = UrlEnums.TabKeyPreference.TabRedirected;
                if (isDeleted)
                {
                    // if the tab is actually deleted, downgrade the preference to 'deleted'.  Any other tabs with the same path that
                    // are redirected but not deleted should take preference
                    preference = UrlEnums.TabKeyPreference.TabDeleted;
                }
                //Note ; if anything else is wrong with this url, (ie, wrong alias) then that will be corrected in a redirect
                AddToTabDict(tabIndex,
                                dupCheck,
                                httpAlias,
                                tab.TabPath,
                                substituteRewritePath,
                                tab.TabID,
                                preference,
                                ref tabPathDepth,
                                settings.CheckForDuplicateUrls,
                                isDeleted);
            }

            //check for permanent redirects as specified in the core dnn permanent redirect property
            if (permanentRedirect)
            {
                AddPermanentRedirectToDictionary(tabIndex,
                                                    dupCheck,
                                                    httpAlias,
                                                    tab,
                                                    tabPath,
                                                    ref rewritePath,
                                                    ref tabPathDepth,
                                                    settings.CheckForDuplicateUrls,
                                                    isDeleted);
            }

            // disabled / not active by date / external url pages cannot navigate to settings page
            if (tab.DisableLink || !string.IsNullOrEmpty(tab.Url) ||
               (tab.EndDate < DateTime.Now && tab.EndDate > DateTime.MinValue) ||
               (tab.StartDate > DateTime.Now && tab.StartDate > DateTime.MinValue))
            {
                string settingsUrl = tabPath.Replace("//", "/") + "/ctl/Tab";
                string settingsRewritePath = CreateRewritePath(tab.TabID, "", "ctl=tab");
                AddToTabDict(tabIndex,
                                dupCheck,
                                httpAlias,
                                settingsUrl,
                                settingsRewritePath,
                                tab.TabID,
                                UrlEnums.TabKeyPreference.TabRedirected,
                                ref tabPathDepth,
                                settings.CheckForDuplicateUrls,
                                isDeleted);
            }

            //777: every tab is added to the dictionary, including those that are deleted 

            //inspect the optional tab redirects and add them as well, keeping track if any are '200' status, meaning the standard Url will be 301, if replaced unfriendly is switched on
            //589 : tab with custom 200 redirects not changing base url to 301 statusa
            AddCustomRedirectsToDictionary(tabIndex,
                                                dupCheck,
                                                httpAlias,
                                                tab,
                                                settings,
                                                options,
                                                ref rewritePath,
                                                out tabPathDepth,
                                                ref customAliasesUsed,
                                                isDeleted,
                                                parentTraceId);

            //if auto ascii conversion is on, do that as well
            if (settings.AutoAsciiConvert)
            {
                bool replacedDiacritic;
                string asciiTabPath = TabPathHelper.ReplaceDiacritics(tabPath, out replacedDiacritic);
                if (replacedDiacritic)
                {
                    ActionType existingAction;
                    RedirectTokens.GetActionFromRewritePath(rewritePath, out existingAction);
                    if (settings.RedirectUnfriendly && existingAction != ActionType.Redirect301)
                    {
                        //add in a tab path, with 301, for the version with the diacritics in
                        string diacriticRewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                                ActionType.Redirect301,
                                                                                                RedirectReason.Diacritic_Characters);
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        httpAlias,
                                        tabPath,
                                        diacriticRewritePath,
                                        tab.TabID,
                                        UrlEnums.TabKeyPreference.TabOK,
                                        ref tabPathDepth,
                                        settings.CheckForDuplicateUrls,
                                        isDeleted);
                    }
                    else
                    {
                        //add in the standard version so that the page responds to both the diacritic version
                        AddToTabDict(tabIndex,
                                            dupCheck,
                                            httpAlias,
                                            tabPath,
                                            rewritePath,
                                            tab.TabID,
                                            UrlEnums.TabKeyPreference.TabOK,
                                            ref tabPathDepth,
                                            settings.CheckForDuplicateUrls,
                                            isDeleted);
                    }
                }
                tabPath = asciiTabPath; //switch tabpath to new, ascii-converted version for rest of processing
            }

            //add the 'standard' Url in
            if (tab.TabID == homeTabId && settings.RedirectUnfriendly)
            {
                //home page shoudl be redirected back to the site root
                //899: check for redirect on home page
                rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                ActionType.CheckFor301,
                                                                                RedirectReason.Site_Root_Home);
                AddToTabDict(tabIndex,
                                dupCheck,
                                httpAlias,
                                tabPath,
                                rewritePath,
                                tab.TabID,
                                UrlEnums.TabKeyPreference.TabOK,
                                ref tabPathDepth,
                                settings.CheckForDuplicateUrls,
                                isDeleted);
            }
            else
            {
                if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly)
                {
                    //add in the standard page, but it's a redirect to the customAlias
                    rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                ActionType.Redirect301,
                                                                                RedirectReason.Custom_Tab_Alias);
                    AddToTabDict(tabIndex,
                                    dupCheck,
                                    httpAlias,
                                    tabPath,
                                    rewritePath,
                                    tab.TabID,
                                    UrlEnums.TabKeyPreference.TabRedirected,
                                    ref tabPathDepth,
                                    settings.CheckForDuplicateUrls,
                                    isDeleted);
                }
                else
                {
                    if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly)
                    {
                        //add in the standard page, but it's a redirect to the customAlias
                        rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath,
                                                                                    ActionType.Redirect301,
                                                                                    RedirectReason.Custom_Tab_Alias);
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        httpAlias,
                                        tabPath,
                                        rewritePath,
                                        tab.TabID,
                                        UrlEnums.TabKeyPreference.TabRedirected,
                                        ref tabPathDepth,
                                        settings.CheckForDuplicateUrls,
                                        isDeleted);
                    }
                    else
                    {
                        //add in the standard page to the dictionary
                        //931 : don't replace existing custom url if this is a redirect or a check for redirect
                        ActionType action;
                        var dupCheckPreference = UrlEnums.TabKeyPreference.TabOK;
                        RedirectTokens.GetActionFromRewritePath(rewritePath, out action);
                        if (action == ActionType.CheckFor301 || action == ActionType.Redirect301 || action == ActionType.Redirect302)
                        {
                            dupCheckPreference = UrlEnums.TabKeyPreference.TabRedirected;
                        }
                        AddToTabDict(tabIndex,
                                        dupCheck,
                                        httpAlias,
                                        tabPath,
                                        rewritePath,
                                        tab.TabID,
                                        dupCheckPreference,
                                        ref tabPathDepth,
                                        settings.CheckForDuplicateUrls,
                                        isDeleted);
                    }
                }
            }
            return tabPathDepth;
        }
Esempio n. 54
0
        internal void StorePageIndexInCache(SharedDictionary<string, string> tabDictionary,
                                             SharedDictionary<int, PathSizes> portalDepthInfo,
                                             FriendlyUrlSettings settings,
                                             string reason)
        {
            onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback) RemovedPageIndexCallBack : null;

            //get list of portal ids for the portals we are storing in the page index
            var portalIds = new List<int>();
            using (portalDepthInfo.GetReadLock())
            {
                portalIds.AddRange(portalDepthInfo.Keys);
            }

            //783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex.
            SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(GetTabsCacheDependency(portalIds)), settings, onRemovePageIndex);

            SetPageCache(PageIndexDepthKey, portalDepthInfo, settings);

            LogRemovedReason = settings.LogCacheMessages;

            if (settings.LogCacheMessages)
            {
                var elc = new EventLogController();
                var logValue = new LogInfo {LogTypeKey = "HOST_ALERT"};

                logValue.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache");
                logValue.AddProperty("Reason", reason);
                logValue.AddProperty("Cache Item Key", PageIndexKey);
                using (tabDictionary.GetReadLock())
                {
                    logValue.AddProperty("Item Count", tabDictionary.Count.ToString());
                }
                logValue.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString());
                elc.AddLog(logValue);
            }
        }
Esempio n. 55
0
        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));
            }
        }
Esempio n. 56
0
 internal static void StorePortalAliasesInCache(SharedDictionary <string, PortalAliasInfo> aliases, FriendlyUrlSettings settings)
 {
     SetPortalCache(PortalAliasListKey, aliases, settings);
 }
Esempio n. 57
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);
        }
Esempio n. 58
0
        public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason r)
        {
            cacheItemRemovedReason = r;
#if (DEBUG)
            if (LogRemovedReason)
            {
                var log = new LogInfo {
                    LogTypeKey = "HOST_ALERT"
                };

                string        itemName;
                string        count;
                List <string> portalCounts = null;
                switch (k)
                {
                case "DNN_" + PageIndexKey:
                    itemName = "Page Index";
                    //user profile actions
                    try
                    {
                        DataCache.RemoveCache(UserProfileActionsKey);
                    }
                    catch (ConfigurationErrorsException)
                    {
                        //do nothing, this means the web.config file was overwritten, and thus the cache
                        //was cleared.
                    }
                    if (v != null && v.GetType() == typeof(SharedDictionary <string, string>))
                    {
                        count = "Item Count: " + ((SharedDictionary <string, string>)v).Values.Count.ToString();
                    }
                    else
                    {
                        count = "N/a";
                    }

                    break;

                case "DNN_" + UrlDictKey:
                    itemName = "Friendly Url List";
                    if (v != null &&
                        v.GetType() == typeof(SharedDictionary <int, SharedDictionary <string, string> >))
                    {
                        var friendlyUrls = (SharedDictionary <int, SharedDictionary <string, string> >)v;
                        portalCounts = new List <string>();
                        using (friendlyUrls.GetReadLock())
                        {
                            count = "Portal Count: " + friendlyUrls.Count.ToString();
                            foreach (int key in friendlyUrls.Keys)
                            {
                                SharedDictionary <string, string> portalUrls = friendlyUrls[key];
                                using (portalUrls.GetReadLock())
                                {
                                    portalCounts.Add("Portal " + key.ToString() + " Item Count :" + portalUrls.Count.ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        count = "N/a";
                    }
                    break;

                default:
                    itemName = "Url Rewriter Cache Item";
                    count    = "";
                    break;
                }
                //add log values
                log.AddProperty("Url Rewriting Caching Message", itemName + " Cache item Removed.");
                log.AddProperty("Reason", cacheItemRemovedReason.ToString());
                log.AddProperty("Cache Item Key", k);
                log.AddProperty("Item Count", count);
                if (portalCounts != null)
                {
                    int i = 0;
                    foreach (string item in portalCounts)
                    {
                        log.AddProperty("Item " + i.ToString(), item);
                        i++;
                    }
                }
                //System.Diagnostics.Trace.Assert(k != null, "k == " + k);
                LogController.Instance.AddLog(log);
            }
#endif
        }
Esempio n. 59
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
                            PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId);
                            if (alias != null)
                            {
                                string customHttpAlias = alias.HTTPAlias;
                                url = customHttpAlias + "::" + url;
                            }
                        }
                        string cultureKey = redirect.CultureCode.ToLowerInvariant();
                        var    locales    = LocaleController.Instance.GetLocales(portalId).Values;
                        if (String.IsNullOrEmpty(cultureKey))
                        {
                            //Add entry for each culture
                            foreach (Locale locale in locales)
                            {
                                AddEntryToDictionary(existingTabs, portalId, tab, locale.Code.ToLowerInvariant(), url);
                            }
                        }
                        else
                        {
                            AddEntryToDictionary(existingTabs, portalId, tab, cultureKey, url);
                        }
                    }
                }
            }
            return(existingTabs);
        }
Esempio n. 60
0
 internal void GetPageIndexFromCache(out SharedDictionary<string, string> dict,
                                     out SharedDictionary<int, PathSizes> portalDepthInfo,
                                     FriendlyUrlSettings settings)
 {
     object raw = DataCache.GetCache(PageIndexKey);
     if (raw != null)
     {
         dict = (SharedDictionary<string, string>)raw;
         raw = DataCache.GetCache(PageIndexDepthKey);
         portalDepthInfo = (SharedDictionary<int, PathSizes>)raw;
     }
     else
     {
         dict = null;
         portalDepthInfo = null;
     }
 }