Exemplo n.º 1
0
        /// <summary>
        /// Refreshes the internally-cached collection of URL templates and redirection mappings.
        /// </summary>
        protected void RefreshUrlMappingData()
        {
            if (_coll != null)
            {
                _coll.Clear();
            }
            else
            {
                _coll = new UrlMappingItemCollection();
            }


            // make a connection to the database and execute the SQL stored procedure
            // to retrieve the listing of URL items in the form
            // [Name], [UrlTemplate], [Redirection]

            using (SqlConnection con = new SqlConnection(GetConnectionString()))
            {
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = _procName;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet        ds = new DataSet();
                    da.Fill(ds);
                    da.Dispose();

                    if (ds.Tables.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DataRow        r = ds.Tables[0].Rows[i];
                            UrlMappingItem item
                                = UrlMappingHelper.CreateTemplatedMappingItem(
                                      r["Name"].ToString(), r["UrlTemplate"].ToString(), r["Redirection"].ToString(), _qsBehavior
                                      );

                            _coll.Add(item);
                        }
                    }
                }
            }

            // if we're using a sqlDependency, generate it now
            if (_useDependency)
            {
                _sqlDependency = new SqlCacheDependency(_dependencyName, _tableName);
                HttpContext.Current.Cache.Insert(kCACHE_KEY, "dummyValue", _sqlDependency, DateTime.Now.AddDays(10), Cache.NoSlidingExpiration);
            }

            // remember the refresh time
            _latestRefresh = System.DateTime.Now;
        }
Exemplo n.º 2
0
        public void AddMapping(string siteKey, UrlMappingItem item)
        {
            UrlMappingItemCollection coll;

            if (_manualItems.ContainsKey(siteKey))
            {
                coll = _manualItems[siteKey];
            }
            else
            {
                coll = new UrlMappingItemCollection();
                _manualItems[siteKey] = coll;
            }

            coll.Merge(item);
        }
Exemplo n.º 3
0
        protected void RefreshUrlMappingData()
        {
            if (HttpContext.Current.Cache[kCACHE_KEY] != null)
            {
                return;
            }

            lock (_synclock)
            {
                if (HttpContext.Current.Cache[kCACHE_KEY] != null)
                {
                    return;
                }

                _urlMappings.Clear();
                _menuItems.Clear();

                List <string> routefiles = new List <string>();

                string root = ServerUtil.MapPath("~");

                foreach (var item in AreaInitializer.Areas.Keys)
                {
                    if (item.Equals("/"))
                    {
                        routefiles.Add(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                    }
                    else
                    {
                        routefiles.Add(Path.Combine(root, item.Substring(1) + Path.DirectorySeparatorChar + "routes.config"));
                    }
                }

                foreach (var item in routefiles)
                {
                    string vp = Path.GetFileName(Path.GetDirectoryName(item)).ToLowerInvariant();
                    if (string.Equals(vp, "App_Data", StringComparison.InvariantCultureIgnoreCase))
                    {
                        vp = "/";
                    }
                    else
                    {
                        vp = "/" + vp;
                    }

                    if (!AreaInitializer.Areas.ContainsKey(vp))
                    {
                        throw new WebException("virtual path not found: {0}", vp);
                    }

                    IArea site = AreaInitializer.Areas[vp];

                    UrlMappingItemCollection         routes = new UrlMappingItemCollection();
                    Dictionary <int, NavigationItem> menus  = new Dictionary <int, NavigationItem>();

                    XmlUrlMappingProvider.ParseXml(item, routes, menus, IncomingQueryStringBehavior.PassThrough);

                    _urlMappings[site.AreaKey] = routes;
                    _menuItems[site.AreaKey]   = menus;
                }

                _fileDependency = new CacheDependency(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                HttpRuntime.Cache.Insert(kCACHE_KEY, "dummyValue", _fileDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null);

                _latestRefresh = DateTime.Now;
            }
        }
        public void AddMapping(string siteKey, UrlMappingItem item)
        {
            UrlMappingItemCollection coll;

            if (_manualItems.ContainsKey(siteKey))
                coll = _manualItems[siteKey];
            else
            {
                coll = new UrlMappingItemCollection();
                _manualItems[siteKey] = coll;
            }

            coll.Merge(item);
        }
        protected void RefreshUrlMappingData()
        {
            if (HttpContext.Current.Cache[kCACHE_KEY] != null)
                return;

            lock (_synclock)
            {
                if (HttpContext.Current.Cache[kCACHE_KEY] != null) return;

                _urlMappings.Clear();
                _menuItems.Clear();

                // clear url mapping cache
                UrlMappingModule.Instance._caches.Clear();

                List<string> routefiles = new List<string>();

                string root = ServerUtil.MapPath("~");

                foreach (var item in AreaInitializer.Areas.Keys)
                {
                    if (item.Equals("/"))
                        routefiles.Add(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                    else
                        routefiles.Add(Path.Combine(root, item.Substring(1) + Path.DirectorySeparatorChar + "routes.config"));
                }

                foreach (var item in routefiles)
                {
                    string vp = Path.GetFileName(Path.GetDirectoryName(item)).ToLowerInvariant();
                    if (string.Equals(vp, "App_Data", StringComparison.InvariantCultureIgnoreCase))
                        vp = "/";
                    else
                        vp = "/" + vp;

                    if (!AreaInitializer.Areas.ContainsKey(vp))
                        throw new WebException("virtual path not found: {0}", vp);

                    IArea site = AreaInitializer.Areas[vp];

                    UrlMappingItemCollection routes = new UrlMappingItemCollection();
                    Dictionary<int, NavigationItem> menus = new Dictionary<int, NavigationItem>();

                    XmlUrlMappingProvider.ParseXml(item, routes, menus, IncomingQueryStringBehavior.PassThrough);

                    _urlMappings[site.AreaKey] = routes;
                    _menuItems[site.AreaKey] = menus;
                }

                _fileDependency = new CacheDependency(Path.Combine(root, "App_Data" + Path.DirectorySeparatorChar + "routes.config"));
                HttpRuntime.Cache.Insert(kCACHE_KEY, "dummyValue", _fileDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null);

                _latestRefresh = DateTime.Now;
            }
        }
        public static void ParseXml(string file, UrlMappingItemCollection routes, Dictionary<int, NavigationItem> menuItems, IncomingQueryStringBehavior incomingQueryStringBehavior)
        {
            if (!File.Exists(file))
                return;

            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(file);
            }
            catch (Exception ex)
            {
                throw new UrlMappingException("The error occurred while loading the route files.  A virtual path is required and the file must be well-formed.", ex);
            }

            menuItems.Clear();

            int i = -1, j = -1, k = -1;
            foreach (XmlNode node in xml.DocumentElement.ChildNodes)
            {
                if (node.Name == "menu")
                {
                    i++;
                    NavigationItem menuItem = getMenuItem(node);
                    menuItem.Children = new Dictionary<int, NavigationItem>();

                    menuItems[i] = menuItem;

                    foreach (XmlNode subNode in node.ChildNodes)
                    {
                        if (subNode.Name == "menu")
                        {
                            j++;
                            NavigationItem sub_menuItem = getMenuItem(subNode);
                            sub_menuItem.Children = new Dictionary<int, NavigationItem>();

                            menuItems[i].Children[j] = sub_menuItem;

                            foreach (XmlNode subsubNode in subNode.ChildNodes)
                            {
                                if (subsubNode.Name == "menu")
                                {
                                    k++;
                                    NavigationItem subsub_menuItem = getMenuItem(subsubNode);
                                    sub_menuItem.Children[k] = subsub_menuItem;

                                    foreach (XmlNode last_node in subsubNode.ChildNodes)
                                    {
                                        if (last_node.Name == "url")
                                        {
                                            UrlMappingItem url = getUrlInfo(last_node, subsub_menuItem, i, j, k, incomingQueryStringBehavior);

                                            routes.Add(url);
                                        }
                                    }
                                }
                                else if (subsubNode.Name == "url")
                                {
                                    UrlMappingItem url = getUrlInfo(subsubNode, sub_menuItem, i, j, -1, incomingQueryStringBehavior);

                                    routes.Add(url);
                                }
                            }
                        }
                        else if (subNode.Name == "url")
                        {
                            UrlMappingItem url = getUrlInfo(subNode, menuItem, i, -1, -1, incomingQueryStringBehavior);

                            routes.Add(url);
                        }
                    }
                }
                else if (node.Name == "url")
                {
                    UrlMappingItem url = getUrlInfo(node, new NavigationItem(), -1, -1, -1, incomingQueryStringBehavior);

                    routes.Add(url);
                }
            }
        }
        /// <summary>
        /// Refreshes the internally-cached collection of URL templates and redirection mappings.
        /// </summary>
        protected void RefreshUrlMappingData()
        {
            if (_coll != null)
                _coll.Clear();
            else
                _coll = new UrlMappingItemCollection();

            // clear url mapping cache
            UrlMappingModule.Instance._caches.Clear();

            string file = HttpContext.Current.Server.MapPath(config.UrlMappingFile);

            ParseXml(file, _coll, MenuItems, config.IncomingQueryStringBehavior);

            _coll.Merge(_manualAdded);

            // using a file dependency, generate it now
            if (File.Exists(file))
            {
                _fileDependency = new CacheDependency(file);
                HttpContext.Current.Cache.Insert(kCACHE_KEY, "dummyValue", _fileDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null);
            }

            // remember the refresh time
            _latestRefresh = DateTime.Now;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Refreshes the internally-cached collection of URL templates and redirection mappings.
        /// </summary>
        protected void RefreshUrlMappingData()
        {
            if (_coll != null)
            {
                _coll.Clear();
            }
            else
            {
                _coll = new UrlMappingItemCollection();
            }


            // parse the given xml file to retrieve the listing of URL items;
            // the xml file should include tags in the form:
            // <urlMapping name="" urlTemplate="" redirection="" />

            XmlDocument xml  = new XmlDocument();
            string      file = HttpContext.Current.Server.MapPath(_urlMappingFile);

            try
            {
                xml.Load(file);
            }
            catch (Exception ex)
            {
                throw new ProviderException("There is an XmlUrlMappingModule error.  The error occurred while loading the urlMappingFile.  A virtual path is required and the file must be well-formed.", ex);
            }

            // parse the file for <urlMapping> tags
            XmlNodeList nodes = xml.SelectNodes("//urlMapping");

            foreach (XmlNode node in nodes)
            {
                // retrieve name, urlTemplate, and redirection attributes;
                // ensure urlTemplate and redirection are present
                string name        = XmlAttributeValue(node, "name");
                string urlTemplate = XmlAttributeValue(node, "urlTemplate");
                string redirection = XmlAttributeValue(node, "redirection");
                bool   enabled     = XmlAttributeBoolean(node, "enabled", true);

                if (enabled)
                {
                    if (string.IsNullOrEmpty(urlTemplate))
                    {
                        throw new ProviderException("There is an XmlUrlMappingModule error.  All <urlMapping> tags in the mapping file require a 'urlTemplate' attribute.");
                    }

                    if (string.IsNullOrEmpty(urlTemplate))
                    {
                        throw new ProviderException("There is an XmlUrlMappingModule error.  All <urlMapping> tags in the mapping file require a 'redirection' attribute.");
                    }

                    // still here, we can create the item and add to the collection
                    UrlMappingItem item
                        = UrlMappingHelper.CreateTemplatedMappingItem(
                              name, urlTemplate, redirection, _qsBehavior
                              );

                    _coll.Add(item);
                }
            }



            // if we're using a file dependency, generate it now
            if (_useDependency)
            {
                _fileDependency = new CacheDependency(file);
                HttpContext.Current.Cache.Insert(kCACHE_KEY, "dummyValue", _fileDependency);
            }

            // remember the refresh time
            _latestRefresh = System.DateTime.Now;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Process incoming URLs and determine if redirection is appropriate
        /// </summary>
        /// <param name="sender">the application object</param>
        /// <param name="e">event arguments</param>
        protected void ProcessUrl(object sender, EventArgs e)
        {
            HttpApplication app = (sender as HttpApplication);

            if (app != null)
            {
                // should the module ignore this request, based on the extension?
                bool bIgnore = false;
                for (int i = 0; i < _ignoreExtensions.Length; i++)
                {
                    if (_ignoreExtensions[i] != "" && app.Request.FilePath.ToLower().EndsWith(_ignoreExtensions[i]))
                    {
                        bIgnore = true;
                        break;
                    }
                }

                if (!bIgnore)
                {
                    string appPath = app.Request.ApplicationPath.ToLower();

                    // if we want to include the queryString in pattern matching, use RawUrl
                    // otherwise use Path
                    string rawUrl = (_qsBehavior == IncomingQueryStringBehaviorEnum.Include ? app.Request.RawUrl : app.Request.Path);

                    rawUrl = rawUrl.ToLower();

                    // remember the incoming querystring values
                    NameValueCollection incomingQS = app.Request.QueryString;

                    // identify the string to pattern match; this should not include
                    // "~/" or "/" at the front but otherwise should be an application-relative
                    // reference
                    string urlRequested = "";

                    if (appPath != "/" && rawUrl.IndexOf(appPath) == 0)
                    {
                        urlRequested = rawUrl.Substring(appPath.Length);
                    }
                    else
                    {
                        urlRequested = rawUrl;
                    }

                    if (urlRequested.StartsWith("/"))
                    {
                        urlRequested = urlRequested.Substring(1);
                    }

                    Regex removeVD = new Regex("^" + appPath + "/", RegexOptions.IgnoreCase);
                    urlRequested = removeVD.Replace(rawUrl, "");

                    urlRequested = urlRequested.Replace(parameters.Edit_Param + "=" + parameters.Edit_Param_Value, "");

                    Regex r = new Regex("(\\?|\\&)$");
                    urlRequested = r.Replace(urlRequested, "");
                    urlRequested = urlRequested.Replace("?&", "?");


                    // inspect the request and perform redirection as necessary
                    // start by getting the mapping items from the provider
                    // (it is up to the provider to cache these if feasible)
                    UrlMappingItemCollection coll
                        = (_provider != null ? _provider.GetUrlMappings() : new UrlMappingItemCollection());


                    bool matchFound = false;
                    foreach (UrlMappingItem item in coll)
                    {
                        Match match = item.UrlTarget.Match(urlRequested);
                        if (match.Success)
                        {
                            string newPath = item.Redirection;

                            // do we want to add querystring parameters for dynamic mappings?
                            NameValueCollection qs = new NameValueCollection();
                            if (match.Groups.Count > 1)
                            {
                                for (int i = 1; i < match.Groups.Count; i++)
                                {
                                    qs.Add(item.UrlTarget.GroupNameFromNumber(i), match.Groups[i].Value);
                                }
                            }

                            RerouteRequest(app, newPath, qs, incomingQS);

                            // exit the loop
                            matchFound = true;
                            break;
                        }
                    }

                    // if we didn't find a match, take appropriate action
                    if (!matchFound)
                    {
                        switch (_noMatchAction)
                        {
                        case NoMatchActionEnum.PassThrough:
                            // do nothing; allow the request to continut to be processed normally;
                            break;

                        case NoMatchActionEnum.Redirect:
                            RerouteRequest(app, _noMatchRedirectPage, null, incomingQS);
                            break;

                        case NoMatchActionEnum.Return404:
                            app.Response.StatusCode        = 404;
                            app.Response.StatusDescription = "File not found.";
                            break;

                        case NoMatchActionEnum.ThrowException:
                            throw new NoMatchFoundException("No UrlMappingModule match found for url '" + urlRequested + "'.");
                        }
                    }
                }
            }
        }