Beispiel #1
0
        public List <object> GetList(Type type, Dictionary <string, object> clauses)
        {
            if (typeof(Summary).IsAssignableFrom(type))
            {
                List <Type> types;
                if (clauses.ContainsKey("@Types"))
                {
                    types = (List <Type>)clauses["@Types"];
                }
                else
                {
                    types = ContentTypeHierarchy.GetSummaryContainers(type);
                }
                var typeGroups = types
                                 .GroupBy(ct => Registered(ct));
                List <object> res = new List <object>();

                foreach (var typeGroup in typeGroups)
                {
                    clauses["@Types"] = typeGroup.ToList();
                    res.AddRange(typeGroup.Key.GetList(type, clauses));
                }
                return(res);
            }
            return(Registered(type).GetList(type, clauses));
        }
Beispiel #2
0
        /// <summary>
        /// Initialise the core dbcontext, the collator, the repository and the editor redirect for a content type
        /// </summary>
        /// <param name="t">content type</param>
        /// <param name="coll">the collator</param>
        /// <param name="repo">the repository</param>
        /// <param name="redir">the editor redirect</param>
        public void SetupType(Type t, ICollator coll, IRepository repo, DiversionStrategy divert)
        {
            if ((coll ?? this.Registered(null)).ContainerType(t) == t) // type t is its own container, so it may be extended
            {
                System.Extender.RegisterForExtension(t);
            }

            if (!typeof(IContentContainer).IsAssignableFrom(t))
            {
                ContentTypeHierarchy.RegisterType(t);
            }

            if (coll != null)
            {
                coll.System = this.System;
                this.Register(t, coll);
            }

            if (repo != null)
            {
                System.Repository.Register(t, repo);
            }

            if (divert != null)
            {
                DataDiverter.Instance.Register(t, divert);
            }
        }
Beispiel #3
0
        public IEnumerable <PropertyStore> Get(Type type, Dictionary <string, object> clauses, List <string> fields, bool excludeFields)
        {
            if (typeof(Summary).IsAssignableFrom(type))
            {
                if (clauses.ContainsKey("@Type"))
                {
                    return(Registered((Type)clauses["@Type"]).Get(type, clauses, fields, excludeFields));
                }

                List <Type> types;
                if (clauses.ContainsKey("@Types"))
                {
                    types = (List <Type>)clauses["@Types"];
                }
                else
                {
                    types = ContentTypeHierarchy.GetSummaryContainers(type);
                }

                var typeGroups = types
                                 .GroupBy(ct => Registered(ct));
                List <PropertyStore> resAll = new List <PropertyStore>();
                foreach (var typeGroup in typeGroups)
                {
                    clauses["@Types"] = typeGroup.ToList();
                    var res = typeGroup.Key.Get(type, clauses, fields, excludeFields);
                    resAll.AddRange(res);
                }
                return(resAll);
            }
            return(Registered(type).Get(type, clauses, fields, excludeFields));
        }
        /// <summary>
        /// Get the possible patterns for a new url of the given type
        /// </summary>
        /// <param name="datatype">Type as its name as a string</param>
        /// <returns>The patterns as JSON</returns>
        public ActionResult TypePatterns(string datatype)
        {
            Type type     = ContentTypeHierarchy.GetContentType(datatype);
            var  patterns = ContentMap.Instance.GetUrlPatterns(type);

            return(Json(patterns, JsonRequestBehavior.AllowGet));
        }
Beispiel #5
0
        /// <summary>
        /// Standard Startup file initialisation
        /// </summary>
        /// <param name="app">Application Builder</param>
        /// <param name="life">Application Lifetime</param>
        public void Initialise(IApplicationBuilder app, IApplicationLifetime life)
        {
            if (app != null)
            {
                RequestContextManager.Instance = new RequestContextManager(app.ApplicationServices);

                // Initialise user system
                this.SecurityManager = Membership.SecurityManager.Current = app.ApplicationServices.GetService <ISecurityManager>();
                this.SecurityManager.InitialiseDataApi();

                var partManager       = app.ApplicationServices.GetService <ApplicationPartManager>();
                var controllerFeature = new ControllerFeature();
                partManager.PopulateFeature(controllerFeature);
                ContentTypeHierarchy.RegisterControllers(controllerFeature.Controllers);
            }

            Modules.ValidateModules();

            Settings.RunTypeSetup?.Invoke(Collator);
            if (Settings.ApplyDbContext == null) // use SqlServer setup by default
            {
                Settings = Settings.UseDefaultDbContextBuilder((builder, conn) => builder.UseSqlServer(conn));
            }

            Collator.BuildRepository();
            Modules.Initialise(this);

            if (life != null)
            {
                life.ApplicationStopped.Register(Modules.Shutdown);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Configure the data system to map requests for User type onto TUser via Identity mechanisms
        /// </summary>
        public virtual void InitialiseDataApi()
        {
            ContentTypeHierarchy.RegisterType(typeof(User));
            ContentTypeHierarchy.RegisterType(typeof(TUser));

            var sys = LyniconSystem.Instance;

            var extender = LyniconSystem.Instance.Extender;

            extender.RegisterForExtension(typeof(User));
            //extender.RegisterExtensionType(typeof(LyniconIdentityUser));

            var efDSFactory     = new EFDataSourceFactory <TContext>(sys);
            var appDbRepository = new BasicRepository(sys, efDSFactory);

            efDSFactory.DbSetSelectors[typeof(TUser)] = db => db.Users.AsNoTracking();
            efDSFactory.ContextLifetimeMode           = ContextLifetimeMode.PerCall;

            // We DON'T want to register TUser with CompositeTypeManager
            var basicCollator = new BasicCollator(sys);

            Collator.Instance.Register(typeof(TUser), new BasicCollator(sys));
            Repository.Instance.Register(typeof(TUser), appDbRepository);

            // override existing collator registration for User
            var identityAdaptorCollator = new IdentityAdaptorCollator <TUser, TUserManager>(sys);

            Collator.Instance.Register(typeof(User), identityAdaptorCollator);
            //Repository.Instance.Register(typeof(User), new BasicRepository());
        }
Beispiel #7
0
        /// <summary>
        /// Get the possible patterns for a new url of the given type
        /// </summary>
        /// <param name="datatype">Type as its name as a string</param>
        /// <returns>The patterns as JSON</returns>
        public IActionResult TypePatterns(string datatype)
        {
            Type type     = ContentTypeHierarchy.GetContentType(datatype);
            var  patterns = RouteData.GetTemplatePatterns(type);

            return(Json(patterns));
        }
        public LyniconSystemFixture()
        {
            ContentTypeHierarchy.RegisterControllersFromAssemblies(new List <Assembly> {
                this.GetType().GetTypeInfo().Assembly
            });
            LyniconSystem = new LyniconSystem(new LyniconSystemOptions()
                                              .UseTypeSetup(col =>
            {
                col.SetupTypeForBasic <TestData>();
                col.SetupType <HeaderContent>();
                col.SetupType <HeaderContent2>();
                col.SetupType <Sub1TContent>();
                col.SetupType <Sub2TContent>();
                col.SetupType <RefContent>();
                col.SetupType <RefTargetContent>();
                col.SetupType <RestaurantContent>();
                col.SetupType <ChefContent>();
                col.SetupType <PathAddressData>();
                col.SetupType <SplitAddressData>();
                col.SetupType <PropertyRedirectContent>();
                col.SetupTypeForBasic <RedirectData>();
                col.SetupType <RedirectTargetContent>();
                col.SetupType <SingleContent>();
                col.System.Repository.Register(null, new ContentRepository(col.System, new MockDataSourceFactory(col.System)));
                col.System.Repository.Register(typeof(TestData), new BasicRepository(col.System, new MockDataSourceFactory(col.System)));
                col.System.Repository.Register(typeof(RedirectData), new BasicRepository(col.System, new MockDataSourceFactory(col.System)));
                col.System.Repository.Register(typeof(ContentItem), new ContentRepository(col.System, new MockDataSourceFactory(col.System)));
            }));

            LyniconSystem.Extender.AddExtensionRule(typeof(TestData), typeof(IExtTestData));
            LyniconSystem.Extender.AddExtensionRule(typeof(ICoreMetadata), typeof(IPublishable));
            LyniconSystem.Extender.AddExtensionRule(typeof(ICoreMetadata), typeof(IInternational));

            LyniconSystem.Construct(new Lynicon.Extensibility.Module[] { new CoreModule(LyniconSystem) });
            LyniconSystem.Modules.SkipDbStateCheck = true;
            LyniconSystem.SetAsPrimarySystem();
            LyniconSystem.Initialise();

            //SetupLyniconSystemWithDb();

            //VersionManager.Instance.RegisterVersion(new TestVersioner());

            var testingRoutes = new RouteCollection();

            testingRoutes.AddTestDataRoute <HeaderContent>("header", "header/{_0}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <TestData>("test-data", "testd/{_0}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <ChefContent>("chef", "header/{_0}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <HeaderContent2>("hc2", "header2", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <SingleContent>("single", "single/{abc}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <RefContent>("ref", "ref/{_0}/{_1}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <RestaurantContent>("rest", "restaurant/{abc}", new { controller = "mock", action = "mock" });
            testingRoutes.AddTestDataRoute <HeaderContent>("header-write", "header-write/{_0}", new { controller = "mock", action = "mock" }, new ContentPermission((roles, data) => true));
            ContentMap.Instance.RouteCollection = testingRoutes;

            VersionManager.Instance.RegisterVersion(new PublishingVersioner(LyniconSystem, t => t == typeof(HeaderContent)));
            VersionManager.Instance.RegisterVersion(new I18nVersioner(LyniconSystem, new string[] { "en-GB", "es-ES" }, "locale", "en-GB", s => s));

            Collator.Instance.SetupType <TestContent>(new TestCollator(), null);
        }
Beispiel #9
0
        /// <summary>
        /// Get markup to refresh an individual item on the List page
        /// </summary>
        /// <param name="datatype">Type of the item</param>
        /// <param name="id">Id of the item</param>
        /// <returns>Markup for the item</returns>
        public ActionResult GetItem(string datatype, string id)
        {
            ViewData.Add("UrlPermission", LyniconSecurityManager.Current.CurrentUserInRole(Lynicon.Membership.User.EditorRole));
            Type type = ContentTypeHierarchy.GetContentType(datatype);
            var  summ = Collator.Instance.Get <Summary>(new ItemId(type, id));

            return(PartialView("ItemListSummary", summ));
        }
Beispiel #10
0
 /// <summary>
 /// Constructs an address from a serialized string form (created via .ToString())
 /// </summary>
 /// <param name="serialized">the serialized string</param>
 public Address(string serialized)
 {
     this.Type = ContentTypeHierarchy.GetContentType(serialized.UpTo(":"));
     foreach (string kvpStr in serialized.After(":").Split('&'))
     {
         this.Add(HttpUtility.UrlDecode(kvpStr.UpTo("=")),
                  HttpUtility.UrlDecode(kvpStr.After("=")));
     }
 }
Beispiel #11
0
        /// <summary>
        /// Adds a PageRoute with DataRoute functionality for providing data to routes in a classic ASP.Net application
        /// </summary>
        /// <typeparam name="TData">The type of the content data attached by the PageDataRoute</typeparam>
        /// <param name="routes">The route collection</param>
        /// <param name="name">Name of the route table entry</param>
        /// <param name="url">The url matching pattern</param>
        /// <param name="pageUrl">The url of the .aspx page template</param>
        /// <returns>The PageDataRoute that was created and registered</returns>
        static public DataRoute <TData> AddPageDataRoute <TData>(this RouteCollection routes, string name, string url, string pageUrl)
            where TData : class, new()
        {
            ContentTypeHierarchy.RegisterType(typeof(TData));
            var route = new DataRoute <TData>(url, new RouteValueDictionary(), new PageRouteHandler(pageUrl));

            routes.Add(name, route);
            return(route);
        }
        /// <summary>
        /// Configure the data system to map requests for User type onto TUser via Identity mechanisms
        /// </summary>
        public virtual void InitialiseDataApi()
        {
            ContentTypeHierarchy.RegisterType(typeof(User));
            var sys = LyniconSystem.Instance;

            sys.Extender.RegisterForExtension(typeof(User));

            Collator.Instance.Register(typeof(User), new BasicCollator(sys));
            Repository.Instance.Register(typeof(User), new BasicRepository(sys, new CoreDataSourceFactory(sys)));
        }
Beispiel #13
0
        /// <summary>
        /// Add a DataRoute to an RouteCollection with route name, url pattern, default values and constraints
        /// </summary>
        /// <typeparam name="TData">The type of the content data attached by the DataRoute</typeparam>
        /// <param name="routes">A RouteCollection to add the route to</param>
        /// <param name="name">Name of the route table entry</param>
        /// <param name="url">The url matching pattern</param>
        /// <param name="defaults">Default values for unmatched pattern elements</param>
        /// <param name="constraints">Constraints for when the route should match</param>
        /// <returns>The DataRoute that was created and registered</returns>
        static public DataRoute <TData> AddDataRoute <TData>(this RouteCollection routes, string name, string url, object defaults, object constraints)
            where TData : class, new()
        {
            ValidateRouteSpec(name, typeof(TData), url, defaults);
            ContentTypeHierarchy.RegisterType(typeof(TData));
            var route = new DataRoute <TData>(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new MvcRouteHandler());

            routes.Add(name, route);
            return(route);
        }
Beispiel #14
0
        //public IEnumerable<string> GetUrls(object item)
        //{
        //    Type type = item.GetType();
        //    if (type == typeof(ContentItem))
        //        type = ContentTypeHierarchy.GetContentType((item as ContentItem).DataType);
        //    var routes = RouteTable.Routes
        //        .OfType<Route>()
        //        .Where(r => r.GetType().IsGenericType
        //            && r.GetType().GetGenericTypeDefinition() == typeof(DataRoute<>)
        //            && r.GetType().GetGenericArguments()[0] == type);
        //    foreach (var route in routes)
        //    {
        //        var urls = GetUrls(route, item);
        //        foreach (string url in urls)
        //            yield return url;
        //    }
        //}
        //public List<string> GetUrls(Route route, object item)
        //{
        //    return Registered(route.GetType().GetGenericArguments()[0]).GetUrls(route, item);
        //}

        public Dictionary <string, string> GetAddress(object item)
        {
            Type type = item.GetType();

            if (item is ContentItem)
            {
                type = ContentTypeHierarchy.GetContentType(((ContentItem)item).DataType);
            }
            return(Registered(type).GetAddress(item));
        }
Beispiel #15
0
 /// <summary>
 /// Get items by a query
 /// </summary>
 /// <typeparam name="T">type of items returned by repository</typeparam>
 /// <param name="targetType">type of items these will produce, and in terms of which the query body is defined</param>
 /// <param name="queryBody">function to apply to a source queryable to filter to the queryable required</param>
 /// <returns>items in containers or the items themselves</returns>
 public IEnumerable <T> Get <T>(Type targetType, Func <IQueryable <T>, IQueryable <T> > queryBody) where T : class
 {
     if (typeof(Summary).IsAssignableFrom(targetType))
     {
         return(Get <T>(targetType, ContentTypeHierarchy.GetSummaryContainers(targetType), queryBody));
     }
     else
     {
         return(Registered(targetType).Get <T>(targetType, new Type[] { targetType }, queryBody));
     }
 }
Beispiel #16
0
        public void Set(Type type, PropertyStore val, object id)
        {
            var query = GetQuery(type, val, id, ProcessQuerySet);

            query.ShouldInsert = false; //
            int affected = query.RunUpdateInsert();

            if (affected == 0)                                 // insert
            {
                ContentTypeHierarchy.EnsureContainsType(type); // this might be the first content item of this type in the db
            }
        }
Beispiel #17
0
        /// <summary>
        /// Adds a route to the <see cref="IRouteBuilder"/> configured for data fetching, with the specified name, template, default values, and
        /// data tokens.
        /// </summary>
        /// <param name="routeBuilder">The <see cref="IRouteBuilder"/> to add the route to.</param>
        /// <param name="name">The name of the route.</param>
        /// <param name="template">The URL pattern of the route.</param>
        /// <param name="defaults">
        /// An object that contains default values for route parameters. The object's properties represent the names
        /// and values of the default values.
        /// </param>
        /// <param name="constraints">
        /// An object that contains constraints for the route. The object's properties represent the names and values
        /// of the constraints.
        /// </param>
        /// <param name="dataTokens">
        /// An object that contains data tokens for the route. The object's properties represent the names and values
        /// of the data tokens.
        /// </param>
        /// <param name="writePermission">
        /// A permission object which specifies who can create or edit the content item via this route
        /// </param>
        /// <param name="divertOverride">
        /// A function which checks whether to switch out the default inner router with one which diverts the user
        /// to an editor controller
        /// </param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IRouteBuilder MapDataRoute <T>(
            this IRouteBuilder routeBuilder,
            string name,
            string template,
            object defaults    = null,
            object constraints = null,
            object dataTokens  = null,
            ContentPermission writePermission = null,
            DiversionStrategy divertOverride  = null)
            where T : class, new()
        {
            if (routeBuilder.DefaultHandler == null)
            {
                throw new InvalidOperationException("Default handler must be set");
            }

            var inlineConstraintResolver = (IInlineConstraintResolver)routeBuilder
                                           .ServiceProvider
                                           .GetService(typeof(IInlineConstraintResolver));

            // Interpose a DataFetchingRouter between the classic Route and the DefaultHandler, which
            // tries to fetch the data for the route
            var dataFetchingRouter = new DataFetchingRouter <T>(routeBuilder.DefaultHandler, false, writePermission, divertOverride);

            var dataRoute = new DataRoute(
                dataFetchingRouter,
                name,
                template,
                new RouteValueDictionary(defaults),
                new RouteValueDictionary(constraints),
                new RouteValueDictionary(dataTokens),
                inlineConstraintResolver);

            routeBuilder.Routes.Add(dataRoute);

            // Record the data route on Lynicon's internal RouteCollection used for reverse url generation
            if (ContentMap.Instance.RouteCollection == null)
            {
                ContentMap.Instance.RouteCollection = new RouteCollection();
            }
            ContentMap.Instance.RouteCollection.Add(dataRoute);

            Type registerType = typeof(T);

            if (registerType.IsGenericType() && registerType.GetGenericTypeDefinition() == typeof(List <>))
            {
                registerType = registerType.GetGenericArguments()[0];
            }

            ContentTypeHierarchy.RegisterType(registerType);

            return(routeBuilder);
        }
Beispiel #18
0
        /// <summary>
        /// Get markup to show all the items of a type in a paged box on the List page
        /// </summary>
        /// <param name="datatype">The data type</param>
        /// <returns>Markup of the paged box listing the items</returns>
        public ActionResult GetPage(string datatype)
        {
            ViewData.Add("UrlPermission", LyniconSecurityManager.Current.CurrentUserInRole(Lynicon.Membership.User.EditorRole));
            ViewData.Add("DelPermission", LyniconSecurityManager.Current.CurrentUserInRole(Lynicon.Membership.User.AdminRole));
            Type type          = ContentTypeHierarchy.GetContentType(datatype);
            Type containerType = Collator.Instance.ContainerType(type);
            // invoke Collator.Instance.GetList<Summary, type>(new Type[] { type }, RouteData).ToArray();
            var summs = (IEnumerable <Summary>)ReflectionX.InvokeGenericMethod(Collator.Instance, "GetList", new Type[] { typeof(Summary), containerType }, new Type[] { type }, RouteData);
            var data  = summs.ToArray();

            return(PartialView("ItemPage", data));
        }
        public IActionResult RefQuery(string query, string listId, string allowedVsn)
        {
            var         types         = listId.Split('_').Select(cn => ContentTypeHierarchy.GetContentType(cn)).ToList();
            bool        showType      = types.Count > 1;
            var         qWords        = query.ToLower().Split(new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            ItemVersion maskVsn       = null;
            ItemVersion currMaskedVsn = null;
            bool        versioned     = false;

            if (!string.IsNullOrEmpty(allowedVsn))
            {
                maskVsn = new ItemVersion(allowedVsn);
                ItemVersion curr = sys.Versions.CurrentVersion;
                ItemVersion vsn  = curr.Superimpose(maskVsn);
                currMaskedVsn = curr.Mask(maskVsn);
                sys.Versions.PushState(VersioningMode.Specific, vsn);
                versioned = true;
            }

            try
            {
                var cachedTypes   = types.Where(t => Cache.IsTotalCached(LyniconModuleManager.Instance, t, true)).ToList();
                var uncachedTypes = types.Except(cachedTypes).ToList();
                var items         = Enumerable.Range(0, 1).Select(n => new { label = "", value = "" }).ToList();
                items.Clear();
                if (uncachedTypes.Count > 0)
                {
                    // TO DO add attribute for containers specifying which field or fields to scan for title, add code to create query to scan here
                }
                if (cachedTypes.Count > 0)
                {
                    items.AddRange(Collator.Instance.Get <Summary, Summary>(cachedTypes,
                                                                            iq => iq.Where(s => qWords.All(w => ((s.Title ?? "").ToLower() + " " + s.Type.Name.ToLower()).Contains(w))).Take(30))
                                   .Select(summ => new
                    {
                        label = summ.Title + (showType ? " (" + LyniconUi.ContentClassDisplayName(summ.Type) + ")" : "")
                                + (versioned && !currMaskedVsn.ContainedBy(summ.Version.Mask(maskVsn)) ? " [" + sys.Versions.DisplayVersion(summ.Version.Mask(maskVsn)).Select(dv => dv.Text).Join(" ") + "]" : ""),
                        value = versioned ? summ.ItemVersionedId.Mask(maskVsn).ToString() : summ.ItemId.ToString()
                    })
                                   .OrderBy(s => s.label));
                }

                return(Json(new { items }));
            }
            finally
            {
                if (versioned)
                {
                    sys.Versions.PopState();
                }
            }
        }
Beispiel #20
0
 /// <summary>
 /// Get items via a query
 /// </summary>
 /// <typeparam name="T">return type, this can be a summmary type, a content type, or a class from which several content types inherit.  The query will be applied across all content types which could output an item of this type.</typeparam>
 /// <typeparam name="TQuery">the type in terms of which the query is expressed: the content type or possibly a class from which several content types inherit</typeparam>
 /// <param name="queryBody">a function which takes an iqueryable and adds the query to the end of it</param>
 /// <returns>list of items of (or cast to) return type</returns>
 public IEnumerable <T> Get <T, TQuery>(Func <IQueryable <TQuery>, IQueryable <TQuery> > queryBody)
     where T : class
     where TQuery : class
 {
     if (typeof(Summary).IsAssignableFrom(typeof(T)))
     {
         return(Get <T, TQuery>(ContentTypeHierarchy.GetSummaryContainers(typeof(T)), queryBody));
     }
     else
     {
         return(Get <T, TQuery>(ContentTypeHierarchy.GetAssignableContentTypes(this, typeof(T)), queryBody));
     }
 }
Beispiel #21
0
        public CoreModule(params string[] dependentOn)
            : base("Core", dependentOn)
        {
            if (!VerifyDbState("LyniconInit 0.1"))
            {
                this.Blocked = true;
                return;
            }

            ContentTypeHierarchy.RegisterType(typeof(User));

            Collator.Instance.SetupType(typeof(ContentItem), null, null);
            Collator.Instance.SetupType(typeof(User), new BasicCollator(Repository.Instance), new UserRepository());
        }
Beispiel #22
0
        /// <summary>
        /// Add a DataRoute to an RouteCollection with route name, url pattern, default values and constraints
        /// </summary>
        /// <typeparam name="TData">The type of the content data attached by the DataRoute</typeparam>
        /// <param name="routes">A RouteCollection to add the route to</param>
        /// <param name="name">Name of the route table entry</param>
        /// <param name="url">The url matching pattern</param>
        /// <param name="defaults">Default values for unmatched pattern elements</param>
        /// <param name="constraints">Constraints for when the route should match</param>
        /// <param name="dataTokens">Data tokens to add to the route</param>
        /// <param name="redirectOverride">An editor redirect to use with this route</param>
        /// <returns>The DataRoute that was created and registered</returns>
        static public DataRoute <TData> AddDataRoute <TData>(this RouteCollection routes, string name, string url, object defaults, object constraints, object dataTokens, IEditorRedirect redirectOverride)
            where TData : class, new()
        {
            ValidateRouteSpec(name, typeof(TData), url, defaults);
            ContentTypeHierarchy.RegisterType(typeof(TData));
            var route = new DataRoute <TData>(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new RouteValueDictionary(dataTokens), new MvcRouteHandler());

            if (redirectOverride != null)
            {
                route.RedirectOverride = redirectOverride;
            }
            routes.Add(name, route);
            return(route);
        }
Beispiel #23
0
        /// <summary>
        /// Get a data item, or list of items, via the route which maps to them
        /// </summary>
        /// <typeparam name="T">type of the item(s), a generic list if a list of items, could be a summary type</typeparam>
        /// <param name="contentType">the content type of the item(s)</param>
        /// <param name="rd">route data</param>
        /// <returns>the mapped items(s)</returns>
        public T Get <T>(Type contentType, RouteData rd) where T : class
        {
            //CodeTimer.MarkTime("Get via route START");

            try
            {
                if (typeof(T).IsGenericType() && typeof(T).GetGenericTypeDefinition() == typeof(List <>))
                {
                    Type        elType = typeof(T).GetGenericArguments()[0];
                    ICollator   coll;
                    List <Type> contentTypes;
                    bool        isSummary = typeof(Summary).IsAssignableFrom(elType);
                    if (isSummary)
                    {
                        contentTypes = ContentTypeHierarchy.GetSummaryContainers(elType);
                        if (contentTypes.Select(ct => Registered(ct)).Distinct().Count() != 1)
                        {
                            throw new Exception("Content types containing summary type " + elType.FullName + " dont have 1 unique registered collator, requirement for a dataroute with list type");
                        }

                        coll = Registered(contentTypes.First());
                    }
                    else
                    {
                        coll         = Registered(elType);
                        contentTypes = new List <Type> {
                            elType
                        };
                    }

                    T itemList = (T)ReflectionX.InvokeGenericMethod(coll, "GetList",
                                                                    new Type[] { elType, isSummary ? elType : ContainerType(elType) },
                                                                    contentTypes,
                                                                    rd);
                    return(itemList);
                }
                else
                {
                    ICollator coll = Registered(contentType);
                    return(coll.Get <T>(new List <Address> {
                        coll.GetAddress(contentType, rd)
                    }).FirstOrDefault());
                }
            }
            finally
            {
                //CodeTimer.MarkTime("Get via route END");
            }
        }
Beispiel #24
0
        /// <summary>
        /// Add a DataRoute to an AreaRegistractionContext with route name, url pattern, default values and specific EditorRedirect to use
        /// </summary>
        /// <typeparam name="TData">The type of the content data attached by the DataRoute</typeparam>
        /// <param name="areaReg">An AreaRegistrationContext</param>
        /// <param name="name">Name of the route table entry</param>
        /// <param name="url">The url matching pattern</param>
        /// <param name="defaults">Default values for unmatched pattern elements</param>
        /// <param name="constraints">Constraints for when the route should match</param>
        /// <param name="dataTokens">Data tokens to add to the route</param>
        /// <param name="redirectOverride">An editor redirect to use with this route</param>
        /// <returns>The DataRoute that was created and registered</returns>
        static public DataRoute <TData> AddDataRoute <TData>(this AreaRegistrationContext areaReg, string name, string url, object defaults, object constraints, object dataTokens, IEditorRedirect redirectOverride)
            where TData : class, new()
        {
            ValidateRouteSpec(name, typeof(TData), url, defaults);
            ContentTypeHierarchy.RegisterType(typeof(TData));
            DataRoute <TData> route = areaReg.Routes.AddDataRoute <TData>(name, url, defaults, constraints, dataTokens, redirectOverride);

            route.DataTokens["area"] = areaReg.AreaName;

            // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up
            // controllers belonging to other areas
            //bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
            //route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;
            return(route);
        }
Beispiel #25
0
        public static void Initialise()
        {
            // Set up data types here
            ContentTypeHierarchy.RegisterType(typeof(HeaderContent));
            ContentTypeHierarchy.RegisterType(typeof(HeaderContent2));
            ContentTypeHierarchy.RegisterType(typeof(TestData));
            ContentTypeHierarchy.RegisterType(typeof(Sub1TContent));
            ContentTypeHierarchy.RegisterType(typeof(Sub2TContent));
            ContentTypeHierarchy.RegisterType(typeof(RefContent));
            ContentTypeHierarchy.RegisterType(typeof(RefTargetContent));
            ContentTypeHierarchy.RegisterType(typeof(PathAddressData));
            ContentTypeHierarchy.RegisterType(typeof(SplitAddressData));
            ContentTypeHierarchy.RegisterType(typeof(RestaurantContent));
            ContentTypeHierarchy.RegisterType(typeof(ChefContent));

            LyniconModuleManager.Instance.Initialise();
        }
Beispiel #26
0
        /// <summary>
        /// Adds a route to the <see cref="IRouteBuilder"/> configured for data fetching, with the specified name, template, default values, and
        /// data tokens.
        /// </summary>
        /// <param name="routeBuilder">The <see cref="IRouteBuilder"/> to add the route to.</param>
        /// <param name="name">The name of the route.</param>
        /// <param name="template">The URL pattern of the route.</param>
        /// <param name="defaults">
        /// An object that contains default values for route parameters. The object's properties represent the names
        /// and values of the default values.
        /// </param>
        /// <param name="constraints">
        /// An object that contains constraints for the route. The object's properties represent the names and values
        /// of the constraints.
        /// </param>
        /// <param name="dataTokens">
        /// An object that contains data tokens for the route. The object's properties represent the names and values
        /// of the data tokens.
        /// </param>
        /// <param name="divertOverride">
        /// A function which checks whether to switch out the default inner router with one which diverts the user
        /// to an editor controller
        /// </param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IRouteBuilder MapDataRoute <T>(
            this IRouteBuilder routeBuilder,
            string name,
            string template,
            object defaults,
            object constraints,
            object dataTokens,
            Func <IRouter, RouteContext, object, IRouter> divertOverride)
            where T : class, new()
        {
            if (routeBuilder.DefaultHandler == null)
            {
                throw new InvalidOperationException("Default handler must be set");
            }

            var inlineConstraintResolver = (IInlineConstraintResolver)routeBuilder
                                           .ServiceProvider
                                           .GetService(typeof(IInlineConstraintResolver));

            // Interpose a DataFetchingRouter between the classic Route and the DefaultHandler, which
            // tries to fetch the data for the route
            var dataFetchingRouter = new DataFetchingRouter <T>(routeBuilder.DefaultHandler, false, divertOverride);

            var dataRoute = new DataRoute(
                dataFetchingRouter,
                name,
                template,
                new RouteValueDictionary(defaults),
                new RouteValueDictionary(constraints),
                new RouteValueDictionary(dataTokens),
                inlineConstraintResolver);

            routeBuilder.Routes.Add(dataRoute);

            // Record the data route on Lynicon's internal RouteCollection used for reverse url generation
            if (ContentMap.Instance.RouteCollection == null)
            {
                ContentMap.Instance.RouteCollection = new RouteCollection();
            }
            ContentMap.Instance.RouteCollection.Add(dataRoute);

            ContentTypeHierarchy.RegisterType(typeof(T));

            return(routeBuilder);
        }
Beispiel #27
0
        /// <summary>
        /// Construct an ItemId by deserializing it from a string (created via .ToString())
        /// </summary>
        /// <param name="s">Serialized ItemId</param>
        public ItemId(string s)
        {
            if (string.IsNullOrEmpty(s) || !s.Contains(":"))
            {
                return;
            }

            string[] parts   = s.Split(':');
            var      idStr   = parts[0].Trim();
            var      typeStr = parts[1].Trim();

            if (string.IsNullOrEmpty(idStr) || string.IsNullOrEmpty(typeStr))
            {
                return;
            }
            this.Id   = idStr;
            this.Type = ContentTypeHierarchy.GetContentType(typeStr);
        }
Beispiel #28
0
        /// <summary>
        /// Construct an ItemId by deserializing it from a string (created via .ToString())
        /// </summary>
        /// <param name="s">Serialized ItemId</param>
        public ItemId(string s)
        {
            if (string.IsNullOrEmpty(s) || !s.Contains(":"))
            {
                throw new ArgumentException("Serialized ItemId in wrong format: " + (s ?? "NULL"));
            }

            string[] parts   = s.Split(':');
            var      idStr   = parts[0].Trim();
            var      typeStr = parts[1].Trim();

            if (string.IsNullOrEmpty(idStr) || string.IsNullOrEmpty(typeStr))
            {
                throw new ArgumentException("Serialized ItemId in wrong format: " + (s ?? "NULL"));
            }
            this.Id   = idStr;
            this.Type = ContentTypeHierarchy.GetContentType(typeStr);
        }
        /// <summary>
        /// Configure the data system to map requests for User type onto TUser via Identity mechanisms
        /// </summary>
        public virtual void InitialiseDataApi()
        {
            ContentTypeHierarchy.RegisterType(typeof(TUser));
            CompositeTypeManager.Instance.RegisterExtensionType(typeof(LyniconIdentityUser));

            var efDSFactory     = new EFDataSourceFactory <TContext>();
            var appDbRepository = new BasicRepository(efDSFactory);

            efDSFactory.DbSetSelectors[typeof(TUser)] = db => db.Users.Include(u => u.Roles);
            efDSFactory.ContextLifetimeMode           = ContextLifetimeMode.PerCall;

            // We DON'T want to register TUser with CompositeTypeManager
            Collator.Instance.Register(typeof(TUser), new BasicCollator(Repository.Instance));
            Repository.Instance.Register(typeof(TUser), appDbRepository);

            // override existing collator registration for User
            var identityAdaptorCollator = new IdentityAdaptorCollator <TUser, TUserManager>(GetUserManager);

            identityAdaptorCollator.Repository = Repository.Instance;
            Collator.Instance.Register(typeof(User), identityAdaptorCollator);
        }
Beispiel #30
0
        /// <summary>
        /// Process all content items using a contentProcessor
        /// </summary>
        /// <typeparam name="T">Type to which all content items must be assigned</typeparam>
        /// <param name="contentProcessor">Set of methods for processing content</param>
        public static void ProcessLoop <T>(this IContentProcessor contentProcessor) where T : class
        {
            log.InfoFormat("**Process all for {0} begins", contentProcessor.Name);

            var contentTypes = ContentTypeHierarchy.GetAssignableContentTypes(typeof(T));

            foreach (Type t in contentTypes)
            {
                Debug.WriteLine("Processing: " + t.FullName);

                foreach (object content in Collator.Instance.Get <object, object>(new Type[] { t }, iq => iq))
                {
                    try
                    {
                        contentProcessor.Process(content);
                        Collator.Instance.Set(null, content, new Dictionary <string, object> {
                            { "setAudit", false }
                        });
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            Summary s = Collator.Instance.GetSummary <Summary>(content);
                            log.Error("Error processing content item " + s.Title + " for " + contentProcessor.Name, ex);
                        }
                        catch
                        {
                            log.Error("Error processing unidentified content item for " + contentProcessor.Name, ex);
                        }
                    }
                }
            }

            log.InfoFormat("**Process all for {0} ends", contentProcessor.Name);
        }