private static void Register(RouteCollection routes, IEnumerable<RouteItem> routeItems) { using (var @lock = routes.GetWriteLock()) { routes.Clear(); foreach (var routeItem in routeItems.Where(r => !r.Disabled)) { routes.Add(routeItem.Name, new RouteAdapter(routeItem)); } } }
/// <summary> /// Register all routes defined in the RouteMappingConfiguration /// </summary> /// <param name="routes">RouteCollection to add routes</param> /// <param name="config">Routes to register</param> public static void RegisterRoutes(RouteCollection routes, RouteMappingConfiguration config) { if (config == null) { throw new NullReferenceException("Route mapping configuration not defined."); } using (routes.GetWriteLock()) { foreach (RouteElement ignoreItem in config.IgnoreRoutes) { routes.IgnoreRoute(ignoreItem.Url); } foreach (RouteElement item in config.Routes) { var lowerCaseOnly = item.LowerCaseOnly == null ? config.Routes.LowerCaseOnly : item.LowerCaseOnly.Value; var route = new StrictRoute(item.Url, new MvcRouteHandler(), lowerCaseOnly); route.Defaults = new RouteValueDictionary(); route.Defaults.Add("Controller", item.Controller); route.Defaults.Add("Action", item.Action); if (item.Defaults != null) { foreach (string key in item.Defaults.AllKeys) { route.Defaults.Add(key, item.Defaults[key].Value); } } if (item.Constraints != null) { route.Constraints = new RouteValueDictionary(); foreach (string key in item.Constraints.AllKeys) { route.Constraints.Add(key, new RegexConstraint(item.Constraints[key].Value)); } } if (item.Namespace != null) { if (route.DataTokens == null) { route.DataTokens = new RouteValueDictionary(); } route.DataTokens["Namespaces"] = new string[] { item.Namespace }; } routes.Add(route); } } }
public static void MapRoutes(RouteCollection routes, ContextualPublishedCache umbracoCache) { //find all articulate root nodes var articulateNodes = umbracoCache.GetByXPath("//Articulate").ToArray(); //NOTE: need to write lock because this might need to be remapped while the app is running if // any articulate nodes are updated with new values using (routes.GetWriteLock()) { //clear the existing articulate routes (if any) RemoveExisting(routes); // For each articulate root, we need to create some custom route, BUT routes can overlap // based on multi-tenency so we need to deal with that. // For example a root articulate node might yield a route like: // / // and another articulate root node that has a domain might have this url: // http://mydomain/ // but when that is processed through RoutePathFromNodeUrl, it becomes: // / // which already exists and is already assigned to a specific node ID. // So what we need to do in these cases is use a special route handler that takes // into account the domain assigned to the route. var groups = articulateNodes .GroupBy(x => RouteCollectionExtensions.RoutePathFromNodeUrl(x.Url)) //This is required to ensure that we create routes that are more specific first // before creating routes that are less specific .OrderByDescending(x => x.Key.Split('/').Length); foreach (var grouping in groups) { var nodesAsArray = grouping.ToArray(); MapRssRoute(routes, grouping.Key, nodesAsArray); MapSearchRoute(routes, grouping.Key, nodesAsArray); MapTagsAndCategoriesRoute(routes, grouping.Key, nodesAsArray); MapMarkdownEditorRoute(routes, grouping.Key, nodesAsArray); foreach (var content in grouping) { MapMetaWeblogRoute(routes, grouping.Key, content); MapManifestRoute(routes, grouping.Key, content); MapRsdRoute(routes, grouping.Key, content); } } } }
public static void RegisterRoutes(RouteCollection routes) { using (routes.GetWriteLock()) { routes.Insert( 0, new Route( CacheTagMvcSettings.RouteUrl, new RouteValueDictionary(new {controller = "CacheTag", action = "Resource"}), new MvcRouteHandler() ) ); routes.Insert( 0, new Route( CacheTagMvcSettings.RouteUrl + ".{ext}", new RouteValueDictionary(new { controller = "CacheTag", action = "Resource", ext = UrlParameter.Optional }), new MvcRouteHandler() ) ); } }
public static void MapRoutes(RouteCollection routes, ContextualPublishedCache umbracoCache) { //find all Dialogue forum root nodes - Testing adding new line var dialogueNodes = umbracoCache.GetByXPath(string.Concat("//", AppConstants.DocTypeForumRoot)).ToArray(); //NOTE: need to write lock because this might need to be remapped while the app is running if // any articulate nodes are updated with new values using (routes.GetWriteLock()) { //clear the existing articulate routes (if any) RemoveExisting(routes); // For each articulate root, we need to create some custom route, BUT routes can overlap // based on multi-tenency so we need to deal with that. // For example a root articulate node might yield a route like: // / // and another articulate root node that has a domain might have this url: // http://mydomain/ // but when that is processed through RoutePathFromNodeUrl, it becomes: // / // which already exists and is already assigned to a specific node ID. // So what we need to do in these cases is use a special route handler that takes // into account the domain assigned to the route. var groups = dialogueNodes.GroupBy(x => RouteCollectionExtensions.RoutePathFromNodeUrl(x.Url)); foreach (var grouping in groups) { var nodesAsArray = grouping.ToArray(); MapTopicRoute(routes, grouping.Key, nodesAsArray); MapDialoguePages(routes, grouping.Key, nodesAsArray); MapMemberRoute(routes, grouping.Key, nodesAsArray); } } }
public void Publish(IEnumerable <RouteDescriptor> routes, Func <IDictionary <string, object>, Task> pipeline = null) { var routesArray = routes .OrderByDescending(r => r.Priority) .ToArray(); // this is not called often, but is intended to surface problems before // the actual collection is modified var preloading = new RouteCollection(); foreach (var routeDescriptor in routesArray) { // extract the WebApi route implementation var httpRouteDescriptor = routeDescriptor as HttpRouteDescriptor; if (httpRouteDescriptor != null) { var httpRouteCollection = new RouteCollection(); httpRouteCollection.MapHttpRoute(httpRouteDescriptor.Name, httpRouteDescriptor.RouteTemplate, httpRouteDescriptor.Defaults, httpRouteDescriptor.Constraints); routeDescriptor.Route = httpRouteCollection.First(); } preloading.Add(routeDescriptor.Name, routeDescriptor.Route); } using (_routeCollection.GetWriteLock()) { // HACK: For inserting names in internal dictionary when inserting route to RouteCollection. var routeCollectionType = typeof(RouteCollection); var namedMap = (Dictionary <string, RouteBase>)routeCollectionType.GetField("_namedMap", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_routeCollection); // new routes are added foreach (var routeDescriptor in routesArray) { // Loading session state information. var defaultSessionState = SessionStateBehavior.Default; object extensionId = default(object); if (routeDescriptor.Route is System.Web.Routing.Route) { var route = routeDescriptor.Route as System.Web.Routing.Route; if (route.DataTokens != null && route.DataTokens.TryGetValue("area", out extensionId) || route.Defaults != null && route.Defaults.TryGetValue("area", out extensionId)) { //TODO Extension Handler //extensionDescriptor = _extensionManager.GetExtension(extensionId.ToString()); } } var shellRoute = new ShellRoute(routeDescriptor.Route, _iocManager, pipeline) { IsHttpRoute = routeDescriptor is HttpRouteDescriptor, // SessionState = sessionStateBehavior }; var area = extensionId != null?extensionId.ToString() : string.Empty; if (!namedMap.Any(t => t.Key == area)) { if (routeDescriptor.Route != null) { _routeCollection.Add(shellRoute); } namedMap[routeDescriptor.Name] = shellRoute; } } } }
public void Publish(IEnumerable <RouteDescriptor> routes, Func <IDictionary <string, object>, Task> env) { var routesArray = routes .OrderByDescending(r => r.Priority) .ToArray(); // this is not called often, but is intended to surface problems before // the actual collection is modified var preloading = new RouteCollection(); foreach (var routeDescriptor in routesArray) { // extract the WebApi route implementation var httpRouteDescriptor = routeDescriptor as HttpRouteDescriptor; if (httpRouteDescriptor != null) { var httpRouteCollection = new RouteCollection(); httpRouteCollection.MapHttpRoute(httpRouteDescriptor.Name, httpRouteDescriptor.RouteTemplate, httpRouteDescriptor.Defaults, httpRouteDescriptor.Constraints); routeDescriptor.Route = httpRouteCollection.First(); } preloading.Add(routeDescriptor.Name, routeDescriptor.Route); } using (_routeCollection.GetWriteLock()) { // existing routes are removed while the collection is briefly inaccessable _routeCollection .OfType <HubRoute>() .ToList().ForEach(x => x.ReleaseShell(_shellSettings)); // HACK: For inserting names in internal dictionary when inserting route to RouteCollection. var routeCollectionType = typeof(RouteCollection); var namedMap = (Dictionary <string, RouteBase>)routeCollectionType.GetField("_namedMap", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_routeCollection); // new routes are added foreach (var routeDescriptor in routesArray) { // Loading session state information. var defaultSessionState = SessionStateBehavior.Default; ExtensionDescriptor extensionDescriptor = null; if (routeDescriptor.Route is Route) { object extensionId; var route = routeDescriptor.Route as Route; if (route.DataTokens != null && route.DataTokens.TryGetValue("area", out extensionId) || route.Defaults != null && route.Defaults.TryGetValue("area", out extensionId)) { extensionDescriptor = _extensionManager.GetExtension(extensionId.ToString()); } } else if (routeDescriptor.Route is IRouteWithArea) { var route = routeDescriptor.Route as IRouteWithArea; extensionDescriptor = _extensionManager.GetExtension(route.Area); } if (extensionDescriptor != null) { // if session state is not define explicitly, use the one define for the extension if (routeDescriptor.SessionState == SessionStateBehavior.Default) { Enum.TryParse(extensionDescriptor.SessionState, true /*ignoreCase*/, out defaultSessionState); } } // Route-level setting overrides module-level setting (from manifest). var sessionStateBehavior = routeDescriptor.SessionState == SessionStateBehavior.Default ? defaultSessionState : routeDescriptor.SessionState; var shellRoute = new ShellRoute(routeDescriptor.Route, _shellSettings, _workContextAccessor, _runningShellTable, env) { IsHttpRoute = routeDescriptor is HttpRouteDescriptor, SessionState = sessionStateBehavior }; var area = extensionDescriptor == null ? "" : extensionDescriptor.Id; var matchedHubRoute = _routeCollection.FirstOrDefault(x => { var hubRoute = x as HubRoute; if (hubRoute == null) { return(false); } return(routeDescriptor.Priority == hubRoute.Priority && hubRoute.Area.Equals(area, StringComparison.OrdinalIgnoreCase) && hubRoute.Name == routeDescriptor.Name); }) as HubRoute; if (matchedHubRoute == null) { matchedHubRoute = new HubRoute(routeDescriptor.Name, area, routeDescriptor.Priority, _runningShellTable); int index; for (index = 0; index < _routeCollection.Count; index++) { var hubRoute = _routeCollection[index] as HubRoute; if (hubRoute == null) { continue; } if (hubRoute.Priority < matchedHubRoute.Priority) { break; } } _routeCollection.Insert(index, matchedHubRoute); // HACK: For inserting names in internal dictionary when inserting route to RouteCollection. if (!string.IsNullOrEmpty(matchedHubRoute.Name) && !namedMap.ContainsKey(matchedHubRoute.Name)) { namedMap[matchedHubRoute.Name] = matchedHubRoute; } } matchedHubRoute.Add(shellRoute, _shellSettings); } } }
private static void Config() { HttpRuntime.Cache.Insert(ConfigFilePathDependencyKey, "", new CacheDependency(configFilePath), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, AppInfoCenterConfigFileUpdated); routes.Clear(); routes.RouteExistingFiles = true; action(routes); //Routes.Add("w1", new Route("{page}.aspx", new AspxRouteHandler())); //Routes.Add("w2", new Route("{folder}/{page}.aspx", new AspxRouteHandler())); //Routes.Add("w3", new Route("{page}.ashx", new AspxRouteHandler())); //Routes.Add("w4", new Route("{folder}/{page}.ashx", new AspxRouteHandler())); //Routes.Add("w5", new Route("{page}.asmx", new AspxRouteHandler())); //Routes.Add("w6", new Route("{folder}/{page}.asmx", new AspxRouteHandler())); var config = XDocument.Load(configFilePath); using (routes.GetWriteLock()) { var ignoreUrls = config.Descendants("routeTable").Descendants("ignore").Select(item => item.Attribute("url").Value).ToList(); ignoreUrls.ForEach(url => routes.IgnoreRoute(url)); var addItems = config.Descendants("routeTable").Descendants("add").Select(item => new { Name = item.Attribute("name").Value, Url = item.Attribute("url").Value, Engine = item.Attribute("engine") == null ? "mvc" : item.Attribute("engine").Value.ToLower(), Defaults = item.Descendants("defaults").Elements().Select(sub => new { Name = sub.Name.ToString(), DefaultValue = sub.Value }).ToList(), Constraints = item.Descendants("constraints").Elements().Select(sub => new { Name = sub.Name.ToString(), Pattern = sub.Value }).ToList() }).ToList(); foreach (var item in addItems) { var defaults = new RouteValueDictionary(); foreach (var d in item.Defaults) { if (!defaults.ContainsKey(d.Name)) { if (string.IsNullOrEmpty(d.DefaultValue)) { defaults.Add(d.Name, UrlParameter.Optional); } else { defaults.Add(d.Name, d.DefaultValue); } } } var constraints = new RouteValueDictionary(); foreach (var d in item.Constraints) { if (!constraints.ContainsKey(d.Name)) { constraints.Add(d.Name, d.Pattern); } } if (routes[item.Name] == null) { IRouteHandler handler = new MvcRouteHandler(); if (item.Engine != "mvc") { handler = new AspxRouteHandler(); } routes.Add(item.Name, new Route(item.Url, defaults, constraints, handler)); } } var removeItems = config.Descendants("routeTable").Descendants("remove").Select(item => item.Attribute("name").Value).ToList(); removeItems.ForEach(name => { if (routes[name] != null) { routes.Remove(routes[name]); } }); } }
private void RefreshApplicationData() { // TODO (Roman): try/catch errorhandling? IApplicationContext context = InstanceContainer.ApplicationContext; #region context data context.Refresh(context.BaseDirectory); #endregion #region database content // TODO (Roman): this must be done at the windows service, not at a web client app Dictionary <string, List <IWikiLanguageThreadLookupItem> > wikiLanguageThreadIdLookup = new Dictionary <string, List <IWikiLanguageThreadLookupItem> >(); Dictionary <string, IWikiLanguageThreadLookupItem> wikiLanguageThreadIds = new Dictionary <string, IWikiLanguageThreadLookupItem>(); IApplicationManager applicationManger = InstanceContainer.ApplicationManager; IArticleGroupManager articleGroupManager = InstanceContainer.ArticleGroupManager; IArticleGroupThreadManager articleGroupThreadManager = InstanceContainer.ArticleGroupThreadManager; ISystemProfileImageManager systemProfileImageManager = InstanceContainer.SystemProfileImageManager; IApplication application; IStaticContentLookup staticContentLookup; ArticleGroupThread articleGroupThread; ArticleGroup articleGroup; IApplicationThemeInfo[] applicationThemeInfos = context.GetAllApplicationThemeInfos(); Dictionary <int, IApplication> applicationLookup = new Dictionary <int, IApplication>(); #region applications foreach (IApplicationThemeInfo applicationThemeInfo in applicationThemeInfos) { application = applicationManger.GetApplication(applicationThemeInfo.ApplicationName); if (application == null) { application = new Workmate.Components.Entities.Application(applicationThemeInfo.ApplicationName, "Generated on Application Data Refresh at " + DateTime.UtcNow.ToString() + " (UTC)"); #region do default settings - we really want this to be prepopulated by sql scripts application.DefaultAdminSenderEmailAddress = "admin@" + applicationThemeInfo.ApplicationName + ".com"; #endregion var report = applicationManger.Create(application); if (report.Status != DataRepositoryActionStatus.Success) { // TODO (Roman): error handling? continue; } } // this was not set yet as the context refresh above did not have all data available, so we have to do it here applicationThemeInfo.ApplicationId = application.ApplicationId; applicationThemeInfo.Application = application; applicationLookup[application.ApplicationId] = application; } #endregion #region Userroles string[] userRoles = Enum.GetNames(typeof(UserRole)); foreach (int applicationId in applicationLookup.Keys) { InstanceContainer.WorkmateRoleProvider.CreateRolesIfNotExist(applicationId, userRoles); } #endregion IThemeFolderLookup themeFolderLookup; Dictionary <string, SystemProfileImage> systemProfileImageLookup; HashSet <int> usedApplicationIds = new HashSet <int>(); foreach (IApplicationThemeInfo applicationThemeInfo in applicationThemeInfos.Where(c => c.ApplicationGroup == MagicStrings.APPLICATIONGROUP_NAME_WORKMATE)) { themeFolderLookup = context.GetThemeFolderLookup(applicationThemeInfo.ApplicationGroup); #region profile images if (!usedApplicationIds.Contains(applicationThemeInfo.ApplicationId)) { systemProfileImageLookup = systemProfileImageManager.GetSystemProfileImages(applicationThemeInfo.ApplicationId); if (!systemProfileImageLookup.ContainsKey(MagicStrings.PROFILE_IMAGE_MALE_FILENAME)) { if (File.Exists(applicationThemeInfo.Images.DefaultThemeImageFolderServerPath + MagicStrings.PROFILE_IMAGE_MALE_FILENAME)) { TryCreateSystemProfileImage(themeFolderLookup, applicationThemeInfo , applicationThemeInfo.Images.DefaultThemeImageFolderServerPath + MagicStrings.PROFILE_IMAGE_MALE_FILENAME , MagicStrings.PROFILE_IMAGE_MALE_FILENAME); } } if (!systemProfileImageLookup.ContainsKey(MagicStrings.PROFILE_IMAGE_FEMALE_FILENAME)) { if (File.Exists(applicationThemeInfo.Images.DefaultThemeImageFolderServerPath + MagicStrings.PROFILE_IMAGE_FEMALE_FILENAME)) { TryCreateSystemProfileImage(themeFolderLookup, applicationThemeInfo , applicationThemeInfo.Images.DefaultThemeImageFolderServerPath + MagicStrings.PROFILE_IMAGE_FEMALE_FILENAME , MagicStrings.PROFILE_IMAGE_FEMALE_FILENAME); } } // now reload in case we've created profile images for the first time systemProfileImageLookup = systemProfileImageManager.GetSystemProfileImages(applicationThemeInfo.ApplicationId); foreach (SystemProfileImage systemProfileImage in systemProfileImageLookup.Values) { TrySaveProfileImage(systemProfileImage, applicationThemeInfo, MagicStrings.FOLDER_IMAGES_PROFILE_NORMAL, MagicNumbers.PROFILEIMAGE_SIZE_NORMAL); TrySaveProfileImage(systemProfileImage, applicationThemeInfo, MagicStrings.FOLDER_IMAGES_PROFILE_TINY, MagicNumbers.PROFILEIMAGE_SIZE_TINY); } usedApplicationIds.Add(applicationThemeInfo.ApplicationId); } systemProfileImageLookup = systemProfileImageManager.GetSystemProfileImages(applicationThemeInfo.ApplicationId); foreach (SystemProfileImage systemProfileImage in systemProfileImageLookup.Values) { switch (systemProfileImage.FriendlyFileName) { case MagicStrings.PROFILE_IMAGE_MALE_FILENAME: applicationThemeInfo.Images.MaleSystemProfileImageId = systemProfileImage.ImageId; break; case MagicStrings.PROFILE_IMAGE_FEMALE_FILENAME: applicationThemeInfo.Images.FemaleSystemProfileImageId = systemProfileImage.ImageId; break; } } #endregion #region create wiki language threads articleGroup = articleGroupManager.GetArticleGroup(applicationThemeInfo.ApplicationId, MagicStrings.WIKI_LANGUAGE_SECTION); if (articleGroup == null) { articleGroup = new ArticleGroup(applicationThemeInfo.ApplicationId, MagicStrings.WIKI_LANGUAGE_SECTION, true); articleGroup.Description = "Generated on Application Data Refresh at " + DateTime.UtcNow.ToString() + " (UTC)"; var report = articleGroupManager.Create(articleGroup); if (report.Status != DataRepositoryActionStatus.Success) { // TODO (Roman): error handling? continue; } } wikiLanguageThreadIds = new Dictionary <string, IWikiLanguageThreadLookupItem>(); staticContentLookup = context.GetStaticContentLookup(applicationThemeInfo.ApplicationGroup); foreach (string theme in themeFolderLookup.ThemeNames) { foreach (Language language in staticContentLookup.GetLanguages(theme)) { if (wikiLanguageThreadIds.ContainsKey(language.ShortCode)) { continue; } articleGroupThread = articleGroupThreadManager.GetArticleGroupThread(language.ShortCode); if (articleGroupThread == null) { articleGroupThread = new ArticleGroupThread(articleGroup, ArticleGroupThreadStatus.Enabled, language.ShortCode); articleGroupThread.IsApproved = true; articleGroupThread.IsLocked = false; var report = articleGroupThreadManager.Create(articleGroupThread); if (report.Status != DataRepositoryActionStatus.Success) { // TODO (Roman): error handling? continue; } } wikiLanguageThreadIds[language.ShortCode] = new WikiLanguageThreadLookupItem(language.ShortCode, language.Name, articleGroupThread.ArticleGroupThreadId); } } wikiLanguageThreadIdLookup[applicationThemeInfo.ApplicationName.ToLowerInvariant()] = wikiLanguageThreadIds.Values .ToList(); #endregion } IApplicationDataCache applicationDataCache = InstanceContainer.ApplicationDataCache; applicationDataCache.Refresh(wikiLanguageThreadIdLookup); #endregion #region routes RouteCollection routes = RouteTable.Routes; // TODO (Roman): get read lock as well? using (IDisposable writeLock = routes.GetWriteLock()) { routes.Clear(); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); ISitemapLookup sitemapLookup; Menu topMenu; MenuInfo menuInfo; Dictionary <string, Breadcrumb> breadCrumbs = new Dictionary <string, Breadcrumb>(); foreach (string applicationGroup in context.GetApplicationGroups()) { sitemapLookup = context.GetSitemapLookup(applicationGroup); breadCrumbs.Clear(); CreateBreadcrumbs(breadCrumbs, sitemapLookup); foreach (RouteTag routeTag in sitemapLookup.RouteTags) { topMenu = sitemapLookup.GetMenu(routeTag.TopMenuName); #region data tokens extensions routeTag.DataTokens[MagicStrings.DATATOKENS_BREADCRUMB] = breadCrumbs[routeTag.Name]; routeTag.DataTokens[MagicStrings.DATATOKENS_ROUTENAME] = routeTag.Name; menuInfo = new MenuInfo(); menuInfo.TopMenuName = routeTag.TopMenuName; if (topMenu != null) { foreach (MenuItem item in topMenu.MenuItems) { if (item.RouteName == routeTag.Name) { menuInfo.TopMenuItemName = item.Name; } foreach (MenuItem subItem in item.Children) { if (subItem.RouteName == routeTag.Name) { menuInfo.TopMenuItemName = subItem.Parent.Name; menuInfo.TopMenuSubItemName = subItem.Name; break; } } foreach (MenuItem subItem in item.DropdownMenuItems) { foreach (MenuItem dropdownSubItem in subItem.Children) { if (dropdownSubItem.RouteName == routeTag.Name) { menuInfo.TopMenuItemName = dropdownSubItem.Parent.Name; menuInfo.TopMenuSubItemName = dropdownSubItem.Name; break; } } } } } routeTag.DataTokens[MagicStrings.DATATOKENS_MENUINFO] = menuInfo; #endregion routes.Add( MagicStrings.FormatRouteName(applicationGroup, routeTag.Name) , new Route(routeTag.Url , routeTag.Defaults , routeTag.Constraints , routeTag.DataTokens , routeTag.RouteHandler)); } } } #endregion }
public ActionResult SaveSettings(List <ParamNameValue> ParamNameValues) { List <ParamNameValue> WrongParams = new List <ParamNameValue>(); string GeneralSecretAdminUrlOld = AppParams.GeneralSecretAdminUrl.Value; string AppApiSecretURL = AppParams.AppApiSecretURL.Value; foreach (ParamNameValue Param in ParamNameValues) { if (Param.Name == null || Param.Name.Length == 0) { continue; } Parameter Parameter = Parameters.GetBy(Param.Name); Parameter.MemberID = Profile.Member.MemberID; string oldValue = Parameter.Value; Param.Value = Param.Value == null ? "" : Param.Value; if (Parameter.Type == ParameterType.Bool) { if (Param.Value.ToLower() == "true") { Param.Value = Parameter.Value = "true"; } else { Param.Value = Parameter.Value = "false"; } } else if (Parameter.Type == ParameterType.SmallInteger || Parameter.Type == ParameterType.RadioInteger) { long value = -1; bool result = long.TryParse(Param.Value, out value); Parameter.Value = result ? Param.Value : Parameter.Value; if (!result) { WrongParams.Add(Param); } } else { Parameter.Value = Param.Value; } if (oldValue != Param.Value) { Parameter.Save(); } if (AppParams.GeneralAuditEnabled.Value == "true" && Param.Value != oldValue) { AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("Changed: {0} -> from \"{1}\" to \"{2}\"", Parameter.Name, oldValue, Parameter.Value)); } } AppParams.RefreshAppParameters(); List <ParamNameValue> ParamValues = new List <ParamNameValue>(); List <Parameter> Params = Parameters.Get(); //////////////////////////////////////////// // Change admin route //////////////////////////////////////////// bool AdminRouteChaned = false; string RelativeAdminPath = "{controller}/{action}/{id}"; if (AppParams.GeneralSecretAdminUrl != null && AppParams.GeneralSecretAdminUrl.Value.Length > 0 && GeneralSecretAdminUrlOld != AppParams.GeneralSecretAdminUrl.Value) { RouteCollection routes = RouteTable.Routes; using (routes.GetWriteLock()) { RelativeAdminPath = Path.Combine(AppSession.Parameters.GeneralSecretAdminUrl.Value.Replace("/", "\\"), RelativeAdminPath.Replace("/", "\\")).Replace("\\", "/"); if (RelativeAdminPath[0] == '/') { RelativeAdminPath = RelativeAdminPath.Remove(0, 1); } Route route = (Route)routes["Admin-Secret-Path"]; route.Url = RelativeAdminPath; } // If admin route changed redirect admin to correct url AdminRouteChaned = true; } else if ((AppParams.GeneralSecretAdminUrl == null || AppParams.GeneralSecretAdminUrl.Value.Length == 0) && GeneralSecretAdminUrlOld != AppParams.GeneralSecretAdminUrl.Value) { RouteCollection routes = RouteTable.Routes; using (routes.GetReadLock()) { Route route = (Route)routes["Admin-Secret-Path"]; route.Url = "Admin/" + RelativeAdminPath; } AdminRouteChaned = true; } //////////////////////////////////////////// // Change API route //////////////////////////////////////////// bool APIRouteChaned = false; string RelativeAPIPath = "{action}/{id}"; if (AppParams.AppApiSecretURL != null && AppParams.GeneralSecretAdminUrl.Value.Length > 0 && AppApiSecretURL != AppParams.AppApiSecretURL.Value) { RouteCollection routes = RouteTable.Routes; using (routes.GetWriteLock()) { RelativeAPIPath = Path.Combine(AppSession.Parameters.AppApiSecretURL.Value.Replace("/", "\\"), RelativeAPIPath.Replace("/", "\\")).Replace("\\", "/"); if (RelativeAdminPath[0] == '/') { RelativeAdminPath = RelativeAPIPath.Remove(0, 1); } Route route = (Route)routes["API-Secret-Path"]; route.Url = RelativeAPIPath; } // If API route changed redirect admin to correct url APIRouteChaned = true; } else if ((AppParams.AppApiSecretURL == null || AppParams.AppApiSecretURL.Value.Length == 0) && AppApiSecretURL != AppParams.AppApiSecretURL.Value) { RouteCollection routes = RouteTable.Routes; using (routes.GetReadLock()) { Route route = (Route)routes["API-Secret-Path"]; route.Url = "Admin/API/" + RelativeAPIPath; } APIRouteChaned = true; } foreach (Parameter Param in Params) { ParamValues.Add(new ParamNameValue { Name = Param.Name, Value = Param.Value, Type = Param.Type.ToString() }); } string Message = ""; string AdminUrlChanged = ""; string APIUrlChanged = ""; RequestResultModel _model = new RequestResultModel(); if (AdminRouteChaned) { AdminUrlChanged = String.Format("<br/><strong>Admin URL has been changed. Click <a href=\"{0}\">here</a> to redirect to actual admin URL.</strong>", Url.Action("", "Settings")); } if (APIRouteChaned) { string Path = (AppParams.AppApiSecretURL.Value.Length > 0 ? AppParams.AppApiSecretURL.Value : "Admin/API"); APIUrlChanged = String.Format("<br/>API URL has been changed. Please update all API clients. Here is base url now: <strong>{0}</strong>", Path); } if (WrongParams.Count == 0) { _model.Title = GetLabel("Account.Controller.Congrat"); _model.InfoType = RequestResultInfoType.Success; _model.Message = "Application settngs have been saved." + AdminUrlChanged + APIUrlChanged; Message = this.RenderPartialView(@"_RequestResultDialogInLine", _model); } else { _model.Title = GetLabel("Account.Controller.Warning"); _model.InfoType = RequestResultInfoType.ErrorOrDanger; _model.Message = "Some parametrs have not been saved. Please check." + AdminUrlChanged + APIUrlChanged; Message = this.RenderPartialView(@"_RequestResultDialogInLine", _model); } return(Json(new { Message = Message, Settings = ParamValues, }, JsonRequestBehavior.AllowGet)); }
public void MapRoutes(RouteCollection routes) { using (var umbCtxAccessor = _umbracoContextFactory.EnsureUmbracoContext()) { //find all articulate root nodes var contentCache = umbCtxAccessor?.UmbracoContext?.ContentCache; if (contentCache == null) { throw new InvalidOperationException("Could not create Articulate routes, the content cache instance was null"); } var articulateCt = contentCache.GetContentType("Articulate"); if (articulateCt == null) { return; } var articulateNodes = contentCache.GetByContentType(articulateCt).ToList(); _logger.Info(typeof(ArticulateRoutes), "Mapping routes for {ArticulateRootNodesCount} Articulate root nodes", articulateNodes.Count); //NOTE: need to write lock because this might need to be remapped while the app is running if // any articulate nodes are updated with new values using (routes.GetWriteLock()) { //clear the existing articulate routes (if any) RemoveExisting(routes); // For each articulate root, we need to create some custom route, BUT routes can overlap // based on multi-tenency so we need to deal with that. // For example a root articulate node might yield a route like: // / // and another articulate root node that has a domain might have this url: // http://mydomain/ // but when that is processed through RoutePathFromNodeUrl, it becomes: // / // which already exists and is already assigned to a specific node ID. // So what we need to do in these cases is use a special route handler that takes // into account the domain assigned to the route. var articulateNodesGroupedByUriPath = articulateNodes .GroupBy(x => RouteCollectionExtensions.RoutePathFromNodeUrl(x.Url)) //This is required to ensure that we create routes that are more specific first // before creating routes that are less specific .OrderByDescending(x => x.Key.Split('/').Length); foreach (var nodeByPathGroup in articulateNodesGroupedByUriPath) { var nodesAsArray = nodeByPathGroup.ToArray(); var uriPath = nodeByPathGroup.Key; MapRssRoute(routes, uriPath, nodesAsArray); MapSearchRoute(routes, uriPath, nodesAsArray); MapMarkdownEditorRoute(routes, uriPath, nodesAsArray); MapAuthorsRssRoute(routes, uriPath, nodesAsArray); foreach (var articulateRootNode in nodeByPathGroup) { MapMetaWeblogRoute(routes, uriPath, articulateRootNode); MapManifestRoute(routes, uriPath, articulateRootNode); MapRsdRoute(routes, uriPath, articulateRootNode); MapOpenSearchRoute(routes, uriPath, articulateRootNode); } // tags/cats routes are the least specific MapTagsAndCategoriesRoute(routes, uriPath, nodesAsArray); } } } }
public void Publish(IEnumerable <RouteDescriptor> routes) { var routesArray = routes .OrderByDescending(r => r.Priority) .ToArray(); // this is not called often, but is intended to surface problems before // the actual collection is modified var preloading = new RouteCollection(); foreach (var routeDescriptor in routesArray) { // extract the WebApi route implementation var httpRouteDescriptor = routeDescriptor as HttpRouteDescriptor; if (httpRouteDescriptor != null) { var httpRouteCollection = new RouteCollection(); httpRouteCollection.MapHttpRoute(httpRouteDescriptor.Name, httpRouteDescriptor.RouteTemplate, httpRouteDescriptor.Defaults); routeDescriptor.Route = httpRouteCollection.First(); } preloading.Add(routeDescriptor.Name, routeDescriptor.Route); } using (routeCollection.GetWriteLock()) { // existing routes are removed while the collection is briefly inaccessable var cropArray = routeCollection .OfType <ShellRoute>() .Where(sr => sr.ShellSettingsName == shellSettings.Name) .ToArray(); foreach (var crop in cropArray) { routeCollection.Remove(crop); } // new routes are added foreach (var routeDescriptor in routesArray) { // Loading session state information. var defaultSessionState = SessionStateBehavior.Default; ExtensionDescriptor extensionDescriptor = null; if (routeDescriptor.Route is Route) { object extensionId; var route = routeDescriptor.Route as Route; if (route.DataTokens != null && route.DataTokens.TryGetValue("area", out extensionId) || route.Defaults != null && route.Defaults.TryGetValue("area", out extensionId)) { extensionDescriptor = extensionManager.GetExtension(extensionId.ToString()); } } else if (routeDescriptor.Route is IRouteWithArea) { var route = routeDescriptor.Route as IRouteWithArea; extensionDescriptor = extensionManager.GetExtension(route.Area); } if (extensionDescriptor != null) { // if session state is not define explicitly, use the one define for the extension if (routeDescriptor.SessionState == SessionStateBehavior.Default) { Enum.TryParse(extensionDescriptor.SessionState, true /*ignoreCase*/, out defaultSessionState); } } // Route-level setting overrides module-level setting (from manifest). var sessionStateBehavior = routeDescriptor.SessionState == SessionStateBehavior.Default ? defaultSessionState : routeDescriptor.SessionState; var shellRoute = new ShellRoute(routeDescriptor.Route, shellSettings, workContextAccessor, runningShellTable) { IsHttpRoute = routeDescriptor is HttpRouteDescriptor, SessionState = sessionStateBehavior }; routeCollection.Add(routeDescriptor.Name, shellRoute); } } }
/// <summary> /// 发布路由。 /// </summary> /// <param name="routes">路由集合。</param> public void Publish(IEnumerable <RouteDescriptor> routes) { //排序。 var routesArray = routes .OrderByDescending(r => r.Priority) .ToArray(); //发布前事件。 _routePublisherEventHandlers.Invoke(i => i.Publishing(routesArray), NullLogger.Instance); using (_routeCollection.GetWriteLock()) { //释放现有路由。 _routeCollection .OfType <HubRoute>().Invoke(x => x.ReleaseShell(_shellSettings), NullLogger.Instance); var routeList = new List <RouteBase>(_routeCollection); //添加新路由 foreach (var routeDescriptor in routesArray) { //根据Route得到扩展描述符 ExtensionDescriptorEntry extensionDescriptor = null; if (routeDescriptor.Route is Route) { object extensionId; var route = routeDescriptor.Route as Route; if (route.DataTokens != null && route.DataTokens.TryGetValue("area", out extensionId) || route.Defaults != null && route.Defaults.TryGetValue("area", out extensionId)) { extensionDescriptor = _extensionManager.GetExtension(extensionId.ToString()); } } else if (routeDescriptor.Route is IRouteWithArea) { var route = routeDescriptor.Route as IRouteWithArea; extensionDescriptor = _extensionManager.GetExtension(route.Area); } //加载会话状态信息。 var sessionState = SessionStateBehavior.Default; if (extensionDescriptor != null) { if (routeDescriptor.SessionState == SessionStateBehavior.Default) { var descriptor = extensionDescriptor.Descriptor; if (descriptor.Keys.Contains("SessionState")) { Enum.TryParse(descriptor["SessionState"], true, out sessionState); } } } //设置SessionState var sessionStateBehavior = routeDescriptor.SessionState == SessionStateBehavior.Default ? sessionState : routeDescriptor.SessionState; //创建外壳路由 var shellRoute = new ShellRoute(routeDescriptor.Route, _shellSettings, _webWorkContextAccessor, _runningShellTable) { IsHttpRoute = routeDescriptor is HttpRouteDescriptor, SessionState = sessionStateBehavior }; //区域 var area = extensionDescriptor == null ? string.Empty : extensionDescriptor.Id; //尝试查找已存在的集线器路由 var matchedHubRoute = routeList.FirstOrDefault(x => { var hubRoute = x as HubRoute; if (hubRoute == null) { return(false); } return(routeDescriptor.Priority == hubRoute.Priority && hubRoute.Area.Equals(area, StringComparison.OrdinalIgnoreCase) && hubRoute.Name == routeDescriptor.Name); }) as HubRoute; //创建新的集线器路由。 if (matchedHubRoute == null) { matchedHubRoute = new HubRoute(routeDescriptor.Name, area, routeDescriptor.Priority, _runningShellTable); int index; for (index = 0; index < routeList.Count; index++) { var hubRoute = routeList[index] as HubRoute; if (hubRoute == null) { continue; } if (hubRoute.Priority < matchedHubRoute.Priority) { break; } } routeList.Insert(index, matchedHubRoute); } matchedHubRoute.Add(shellRoute, _shellSettings); } //清空现有路由。 _routeCollection.Clear(); foreach (var item in routeList) { if (item is HubRoute) { _routeCollection.Add((item as HubRoute).Name, item); } else { _routeCollection.Add(item); } } } //发布后事件。 _routePublisherEventHandlers.Invoke(i => i.Published(routesArray), NullLogger.Instance); }