示例#1
0
		public override void Map(Routing.Route route, IContainer container)
		{
			route.ThrowIfNull("route");
			container.ThrowIfNull("container");

			route.ResolveRelativeUrlsUsingFormatString(_format);
		}
示例#2
0
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            route.RestrictByRefererUrlHostTypes(_hostTypes);
        }
示例#3
0
        public void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            _mapper.Map(route, container);
        }
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            route.RestrictByUrlPorts(_ports);
        }
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            route.RestrictByMethods(_methods);
        }
示例#6
0
        public RouteMatchResult(Routing.Route route, MatchResult result)
        {
            route.ThrowIfNull("route");
            result.ThrowIfNull("result");

            _route       = route;
            _matchResult = result;
        }
        public RouteMatchResult(Routing.Route route, MatchResult result)
        {
            route.ThrowIfNull("route");
            result.ThrowIfNull("result");

            _route = route;
            _matchResult = result;
        }
示例#8
0
        public string RenderSystemLink(RenderContext context, Routing.Route route)
        {
            Render.FrontContext frontContext = context.GetItem <Render.FrontContext>();

            route.Parameters = ObjectRoute.ParseParameters(route, this.Url);

            var  constTypeString = route.Parameters.GetValue("objecttype");
            byte constType       = ConstObjectType.Unknown;

            if (!byte.TryParse(constTypeString, out constType))
            {
                constType = ConstTypeContainer.GetConstType(constTypeString);
            }
            var id = route.Parameters.GetValue("nameorid");

            if (constType == ConstObjectType.View)
            {
                var view = context.WebSite.SiteDb().Views.GetByNameOrId(id);

                if (view != null)
                {
                    var relation = context.WebSite.SiteDb().Relations.GetReferredBy(view, ConstObjectType.Page);

                    if (relation != null && relation.Count > 0)
                    {
                        var pageid = relation[0].objectXId;

                        var pageroute = context.WebSite.SiteDb().Routes.GetByObjectId(pageid);

                        if (pageroute != null)
                        {
                            return(RenderPageRoute(context, pageroute));
                        }
                    }
                    /// if view was not rendered within and by the page... try to render with rendercode.
                    if (frontContext.Page != null && frontContext.ExecutingView != null)
                    {
                        string currenturl = context.Request.RelativeUrl;

                        var values = PageRoute.GetViewParameterValues(context.WebSite.SiteDb(), view, frontContext);

                        var alternativeviewcode = Cache.ViewInSamePosition.GetAlternativeCode(frontContext.ExecutingView.Id, view.Id);

                        values.Add(SiteConstants.AlternativeViewQueryName, alternativeviewcode.ToString());
                        return(Kooboo.Lib.Helper.UrlHelper.AppendQueryString(currenturl, values));
                    }

                    else if (frontContext.Page == null)
                    {
                        var values = PageRoute.GetViewParameterValues(context.WebSite.SiteDb(), view, frontContext);

                        return(Kooboo.Lib.Helper.UrlHelper.AppendQueryString(this.Url, values));
                    }
                }
            }
            return(null);
        }
示例#9
0
        public string Route(Guid routeId, params object[] args)
        {
            Routing.Route route = _routes.Value.GetRoute(routeId);

            if (route == null)
            {
                throw new ArgumentException(String.Format("Route with ID '{0}' was not found.", routeId), "routeId");
            }

            return(Absolute(route.ResolveRelativeUrl(args)));
        }
示例#10
0
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            IEnumerable <RestrictionAttribute> attributes = method.GetCustomAttributes <RestrictionAttribute>(false);

            foreach (RestrictionAttribute attribute in attributes)
            {
                attribute.Map(route, container);
            }
        }
示例#11
0
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (_comparer != null)
            {
                route.RestrictByUrlFragments(_fragments, GetComparer(_comparer.Value));
            }
            else
            {
                route.RestrictByUrlFragments(_fragments);
            }
        }
示例#12
0
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (_comparer != null)
            {
                route.RestrictByRefererUrlQueries(_queries, GetComparer(_comparer.Value));
            }
            else
            {
                route.RestrictByRefererUrlQueries(_queries);
            }
        }
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (_nameComparer != null && _valueComparer != null)
            {
                route.RestrictByCookie(_name, GetComparer(_nameComparer.Value), _value, GetComparer(_valueComparer.Value), _optional);
            }
            else
            {
                route.RestrictByCookie(_name, _value, _optional);
            }
        }
示例#14
0
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (_fieldComparer != null && _valueComparer != null)
            {
                route.RestrictByUrlQueryString(_field, GetComparer(_fieldComparer.Value), _value, GetComparer(_valueComparer.Value));
            }
            else
            {
                route.RestrictByUrlQueryString(_field, _value);
            }
        }
示例#15
0
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            HttpMethod httpMethod;
            string     methodName = method.Name.TrimEnd("Async");

            if (Enum <HttpMethod> .TryParse(methodName, true, out httpMethod))
            {
                route.RestrictByMethods(httpMethod);
            }
        }
示例#16
0
        public override void Map(Routing.Route route, IContainer container)
        {
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            var httpRuntime = container.GetInstance <IHttpRuntime>();

            if (_comparer != null)
            {
                route.RestrictByUrlRelativePaths(_relativePaths, GetComparer(_comparer.Value), httpRuntime);
            }
            else
            {
                route.RestrictByUrlRelativePaths(_relativePaths, httpRuntime);
            }
        }
示例#17
0
        public static List <Routing.Route> DefaultRoutes()
        {
            var routes = new List <Routing.Route>();

            Routing.Route systemroute = new Routing.Route();
            systemroute.Name                 = SystemRouteTemplate;
            systemroute.objectId             = "tempid".ToHashGuid();
            systemroute.DestinationConstType = ConstObjectType.KoobooSystem;

            routes.Add(systemroute);

            Routing.Route actionsystemroute = new Routing.Route();
            actionsystemroute.Name                 = SystemRouteTemplateWithAction;
            actionsystemroute.objectId             = "tempid".ToHashGuid();
            actionsystemroute.DestinationConstType = ConstObjectType.KoobooSystem;
            routes.Add(actionsystemroute);

            // add more if needed.
            return(routes);
        }
示例#18
0
        public static void AddPageRoute(SiteDb sitedb, Guid PageId, string relativeurl)
        {
            var oldroute = sitedb.Routes.GetByObjectId(PageId);

            if (oldroute != null)
            {
                Routing.Route newroute = new Routing.Route();
                newroute.Name                 = relativeurl;
                newroute.objectId             = oldroute.Id;
                newroute.DestinationConstType = ConstObjectType.Route;
                sitedb.Routes.appendRoute(newroute, default(Guid));
            }
            else
            {
                Routing.Route route = new Routing.Route();
                route.Name                 = relativeurl;
                route.objectId             = PageId;
                route.DestinationConstType = ConstObjectType.Page;
                sitedb.Routes.appendRoute(route, default(Guid));
            }
        }
示例#19
0
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (!type.NamespaceStartsWith(_rootNamespace))
            {
                return;
            }

            var    pathParts         = new List <string>();
            string relativeNamespace = Regex.Replace(type.Namespace, String.Format(@"^{0}\.?(?<RelativeNamespace>.*)", Regex.Escape(_rootNamespace)), "${RelativeNamespace}");

            pathParts.AddRange(ParseWords(relativeNamespace));
            pathParts.AddRange(ParseWords(type.Name));
            string relativeUrl = String.Join("/", pathParts);

            route.ResolveRelativeUrlsUsingString(relativeUrl);
        }
示例#20
0
        public void Map(Type type, MethodInfo method, Routing.Route route, IContainer container)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");
            container.ThrowIfNull("container");

            if (!type.NamespaceStartsWith(_rootNamespace))
            {
                return;
            }

            var    pathParts         = new List <string>();
            string relativeNamespace = Regex.Replace(type.Namespace, String.Format(@"^{0}\.?(?<RelativeNamespace>.*)", Regex.Escape(_rootNamespace)), "${RelativeNamespace}");

            pathParts.AddRange(ParseWords(relativeNamespace));
            pathParts.AddRange(ParseWords(type.Name));
            string relativePath = String.Join("/", pathParts);
            var    httpRuntime  = container.GetInstance <IHttpRuntime>();

            route.RestrictByUrlRelativePath(relativePath, _caseSensitive ? (IRequestValueComparer)CaseSensitivePlainComparer.Instance : CaseInsensitivePlainComparer.Instance, httpRuntime);
        }
 public abstract void Map(Routing.Route route, IContainer container);
        public async Task <IRouteCollection> GenerateRouteCollectionAsync()
        {
            if (!_assemblies.Any())
            {
                throw new InvalidOperationException("At least one assembly must be provided.");
            }
            if (!_nameMappers.Any())
            {
                throw new InvalidOperationException("At least one name mapper must be provided.");
            }
            if (!_idMappers.Any())
            {
                throw new InvalidOperationException("At least one ID mapper must be provided.");
            }
            if (_relativeUrlResolverMappers.Any() && _container == null)
            {
                throw new InvalidOperationException("Relative URL resolver mappers are configured but no container was provided.");
            }
            if (_restrictionMappers.Any() && _container == null)
            {
                throw new InvalidOperationException("Restriction mappers are configured but no container was provided.");
            }
            if (_customMapperMappers.Any() && _container == null)
            {
                throw new InvalidOperationException("Custom mapper mappers are configured but no container was provided.");
            }

            var routes = new RouteCollection(_duplicateRouteNamesAllowed);
            IEnumerable <Type> matchingTypes = await GetMatchingTypesAsync();

            foreach (Type matchingType in matchingTypes)
            {
                IEnumerable <MethodInfo> matchingMethods = await GetMatchingMethodsAsync(matchingType);

                foreach (MethodInfo matchingMethod in matchingMethods)
                {
                    string name = await GetNameAsync(matchingType, matchingMethod);

                    if (name == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route name for '{0}.{1}'.", matchingType.FullName, matchingMethod.Name));
                    }

                    Guid?id = await GetIdAsync(matchingType, matchingMethod);

                    if (id == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route ID for '{0}.{1}'.", matchingType.FullName, matchingMethod.Name));
                    }

                    Scheme?scheme = await GetSchemeAsync(matchingType, matchingMethod);

                    if (scheme == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route scheme for '{0}.{1}'.", matchingType.FullName, matchingMethod.Name));
                    }

                    var route = new Routing.Route(name, id.Value, scheme.Value);

                    foreach (IRelativeUrlResolverMapper relativeUrlResolverMapper in _relativeUrlResolverMappers)
                    {
                        relativeUrlResolverMapper.Map(matchingType, matchingMethod, route, _container);
                    }
                    foreach (IRestrictionMapper restrictionMapper in _restrictionMappers)
                    {
                        restrictionMapper.Map(matchingType, matchingMethod, route, _container);
                    }
                    foreach (ICustomMapperMapper customMapperMapper in _customMapperMappers)
                    {
                        customMapperMapper.Map(matchingType, matchingMethod, route, _container);
                    }

                    await _responseMapper.MapAsync(() => _container, matchingType, matchingMethod, route);

                    if (_authenticationProvider != null)
                    {
                        bool result = false;

                        foreach (IAuthenticationStrategy authenticationStrategy in _authenticationStrategies)
                        {
                            if (await authenticationStrategy.MustAuthenticateAsync(matchingType, matchingMethod))
                            {
                                result = true;
                                break;
                            }
                        }
                        if (result)
                        {
                            route.AuthenticationProvider(_authenticationProvider);
                        }
                    }

                    routes.Add(route);
                }
            }
            foreach (Func <IRouteCollection, IEnumerable <Routing.Route> > @delegate in _additionalRoutes)
            {
                routes.Add(@delegate(routes));
            }

            return(routes);
        }
示例#23
0
文件: Route.cs 项目: joongonn/mHttp
 internal WebSocketEndpointBuilder(string route)
 {
     Route = new Routing.Route(route);
 }
示例#24
0
        public async Task <IRouteCollection> GenerateRouteCollectionAsync()
        {
            if (!_assemblies.Any())
            {
                throw new InvalidOperationException("At least one assembly must be provided.");
            }
            if (!_nameMappers.Any())
            {
                throw new InvalidOperationException("At least one name mapper must be provided.");
            }
            if (!_idMappers.Any())
            {
                throw new InvalidOperationException("At least one ID mapper must be provided.");
            }
            if (!_resolvedRelativeUrlMappers.Any())
            {
                throw new InvalidOperationException("At least one resolved relative URL mapper must be provided.");
            }
            if (_restrictionMappers.Any() && _restrictionContainer == null)
            {
                throw new InvalidOperationException("Restriction mappers are configured but no restriction container was provided.");
            }

            var routes = new RouteCollection(_duplicateRouteNamesAllowed);
            IEnumerable <Type> matchingTypes = await GetMatchingTypesAsync();

            foreach (Type matchingType in matchingTypes)
            {
                IEnumerable <MethodInfo> matchingMethods = await GetMatchingMethodsAsync(matchingType);

                foreach (MethodInfo matchingMethod in matchingMethods)
                {
                    string name = await GetNameAsync(matchingType, matchingMethod);

                    if (name == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route name for '{0}.{1}'.", matchingType.FullName, matchingMethod.Name));
                    }

                    Guid?id = await GetIdAsync(matchingType, matchingMethod);

                    if (id == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route ID for '{0}.{1}'.", matchingType.FullName, matchingMethod.Name));
                    }

                    Type[] ignoredResolvedRelativeUrlMapperTypes = matchingMethod
                                                                   .GetCustomAttributes <IgnoreResolvedRelativeUrlMapperTypeAttribute>()
                                                                   .SelectMany(arg => arg.IgnoredTypes)
                                                                   .ToArray();
                    string resolvedRelativeUrl = await GetResolvedRelativeUrlAsync(ignoredResolvedRelativeUrlMapperTypes, matchingType, matchingMethod);

                    if (resolvedRelativeUrl == null)
                    {
                        throw new ApplicationException(String.Format("Unable to determine a route resolved relative URL for {0}.{1}.", matchingType.FullName, matchingMethod.Name));
                    }

                    var    route = new Routing.Route(name, id.Value, resolvedRelativeUrl);
                    Type[] ignoredRestrictionMapperTypes = matchingMethod
                                                           .GetCustomAttributes <IgnoreRestrictionMapperTypeAttribute>()
                                                           .SelectMany(arg => arg.IgnoredTypes)
                                                           .ToArray();

                    foreach (IRestrictionMapper restrictionMapper in _restrictionMappers.Where(arg => !ignoredRestrictionMapperTypes.Contains(arg.GetType())))
                    {
                        await restrictionMapper.MapAsync(matchingType, matchingMethod, route, _restrictionContainer);
                    }

                    await _responseMapper.MapAsync(() => _endpointContainer, matchingType, matchingMethod, route);

                    if (_authenticationProvider != null)
                    {
                        bool result = false;

                        foreach (IAuthenticationStrategy authenticationStrategy in _authenticationStrategies)
                        {
                            if (await authenticationStrategy.MustAuthenticateAsync(matchingType, matchingMethod))
                            {
                                result = true;
                                break;
                            }
                        }
                        if (result)
                        {
                            route.AuthenticationProvider(_authenticationProvider);
                        }
                    }

                    routes.Add(route);
                }
            }
            foreach (Func <IRouteCollection, IEnumerable <Routing.Route> > @delegate in _additionalRoutes)
            {
                routes.Add(@delegate(routes));
            }

            return(routes);
        }
示例#25
0
        public Task MapAsync(Func <IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            route.RespondWithNoContent();

            return(Task.Factory.Empty());
        }
 public void Map(Routing.Route route, IContainer container)
 {
 }
示例#27
0
        public void SyncToDb(string FullPath, SiteDb SiteDb, byte[] diskbytes = null, bool logSync = true)
        {
            if (diskbytes == null)
            {
                diskbytes = this.ReadAllBytes(FullPath);
            }
            if (diskbytes == null)
            {
                return;
            }

            if (this.SyncMediator.IsContentHashLock(FullPath, diskbytes))
            {
                return;
            }

            //if (!this.SyncMediator.CheckAndAcquireDiskLock(FullPath, diskbytes))
            //{
            //    return;
            //}
            string OldRelativeUrl = null;
            string RelativeUrl    = null;

            IRepository repo   = null;
            ISiteObject result = null;

            Routing.Route route        = null;
            string        NameFromFile = null;
            string        extension    = UrlHelper.FileExtension(FullPath);

            if (!string.IsNullOrEmpty(extension) && !extension.StartsWith("."))
            {
                extension = "." + extension;
            }
            if (!string.IsNullOrEmpty(extension))
            {
                extension = extension.ToLower();
            }

            var NonRoutable = DiskPathService.GetNonRoutableObject(FullPath);

            if (NonRoutable != null)
            {
                repo         = SiteDb.GetRepository(NonRoutable.StoreName);
                NameFromFile = NonRoutable.Name;
                string name = string.IsNullOrWhiteSpace(NonRoutable.Name) ? NonRoutable.Id.ToString() : NonRoutable.Name;
                if (!string.IsNullOrEmpty(NonRoutable.Extension))
                {
                    extension = NonRoutable.Extension.ToLower();
                    if (!extension.StartsWith("."))
                    {
                        extension = "." + extension;
                    }
                }

                result = repo.GetByNameOrId(name) as ISiteObject;

                if (result == null)
                {
                    if (name.ToLower().EndsWith(extension))
                    {
                        name   = name.Substring(0, name.Length - extension.Length);
                        result = repo.GetByNameOrId(name);
                    }
                    else
                    {
                        name   = name + extension;
                        result = repo.GetByNameOrId(name);
                    }
                }
            }
            else
            {
                OldRelativeUrl = DiskPathService.GetRelativeUrl(SiteDb.WebSite, FullPath);
                RelativeUrl    = Kooboo.Sites.Helper.RouteHelper.ToValidRoute(OldRelativeUrl);

                route = SiteDb.Routes.GetByUrl(RelativeUrl);
                if (route != null)
                {
                    repo   = SiteDb.GetRepository(route.DestinationConstType);
                    result = repo.Get(route.objectId) as ISiteObject;
                }
                else
                {
                    var ModelType = Service.ConstTypeService.GetModelTypeByUrl(RelativeUrl);
                    if (ModelType == null)
                    {
                        return;
                    }
                    repo = SiteDb.GetRepository(ModelType);
                }
                NameFromFile = UrlHelper.FileName(RelativeUrl);
            }

            if (result == null)
            {
                result = Activator.CreateInstance(repo.ModelType) as ISiteObject;
            }

            if (!CheckAssignObject(ref result, diskbytes))
            {
                return;
            }

            if (result is IExtensionable)
            {
                var extensionfile = result as IExtensionable;
                extensionfile.Extension = extension;
            }

            if (string.IsNullOrEmpty(result.Name))
            {
                result.Name = Lib.Helper.StringHelper.ToValidFileName(NameFromFile);
            }

            if (!string.IsNullOrEmpty(RelativeUrl))
            {
                SiteDb.Routes.AddOrUpdate(RelativeUrl, result as SiteObject);
            }

            if (!isSameName(result.Name, NameFromFile, extension) || OldRelativeUrl != RelativeUrl)
            {
                if (File.Exists(FullPath))
                {
                    this.SyncMediator.AbsoluteLock(FullPath);

                    File.Delete(FullPath);

                    this.SyncMediator.LockDisk3Seconds(FullPath);
                    this.SyncMediator.ReleaseAbsoluteLock(FullPath);
                }

                repo.AddOrUpdate(result);
            }

            else

            {
                this.SyncMediator.AcquireDbLock(result.Id);

                repo.AddOrUpdate(result);

                this.SyncMediator.ReleaseDbLock(result.Id);
            }


            if (logSync)
            {
                var coreobject = result as CoreObject;
                SiteDb.Synchronization.AddOrUpdate(new Synchronization {
                    SyncSettingId = SiteDb.Synchronization.DiskSyncSettingId, ObjectId = coreobject.Id, Version = coreobject.Version, StoreName = repo.StoreName
                });
            }
        }
示例#28
0
        // if other routes does not match... find the system route.
        public static Route GetSystemRoute(List <String> segments, SiteDb sitedb = null)
        {
            // public static string SystemRouteTemplate = "/__kb/{objecttype}/{nameorid}"; /{objecttype}/{nameorid}
            // public static string SystemRouteTemplateWithAction = "/__kb/{objecttype}/{nameorid}/{action}";  //{objecttype}/{nameorid}/{action}

            //Routing.Route actionsystemroute = new Routing.Route();
            //actionsystemroute.Name = SystemRouteTemplateWithAction;
            //actionsystemroute.objectId = "tempid".ToHashGuid();
            //actionsystemroute.DestinationConstType = ConstObjectType.KoobooSystem;
            //routes.Add(actionsystemroute);

            if (segments == null || segments.Count < 2)
            {
                return(null);
            }

            string routename = string.Empty;

            var start = segments[0];

            Routing.Route sysRoute = new Routing.Route();
            sysRoute.objectId             = Lib.Security.Hash.ComputeGuidIgnoreCase("___tempid_fake____");
            sysRoute.DestinationConstType = ConstObjectType.KoobooSystem;

            if (start == "__kb")
            {
                if (segments.Count == 3)
                {
                    sysRoute.Name = "/__kb/{objecttype}/{nameorid}";
                }
                else if (segments.Count() == 4)
                {
                    sysRoute.Name = "/__kb/{objecttype}/{nameorid}/{action}";
                }
                else if (segments.Count() > 4)
                {
                    sysRoute.Name = "/__kb/{objecttype}/{path}";
                }
            }
            else
            {
                byte output = 0;

                Kooboo.Data.Interface.IRepository repo = null;
                string nameorid = null;

                if (byte.TryParse(start, out output))
                {
                    if (ConstTypeContainer.ByteTypes.ContainsKey(output))
                    {
                        if (sitedb != null)
                        {
                            repo = sitedb.GetRepository(output);
                        }

                        if (segments.Count == 2)
                        {
                            sysRoute.Name = "/{objecttype}/{nameorid}";
                            nameorid      = segments[1];
                        }
                        else if (segments.Count() == 3)
                        {
                            sysRoute.Name = "/{objecttype}/{nameorid}/{action}";
                            nameorid      = segments[1];
                        }
                    }
                }
                else
                {
                    if (ConstTypeContainer.nameTypes.ContainsKey(start))
                    {
                        if (sitedb != null)
                        {
                            repo = sitedb.GetRepository(start);
                        }

                        if (segments.Count == 2)
                        {
                            sysRoute.Name = "/{objecttype}/{nameorid}";
                            nameorid      = segments[1];
                        }
                        else if (segments.Count() == 3)
                        {
                            sysRoute.Name = "/{objecttype}/{nameorid}/{action}";
                            nameorid      = segments[1];
                        }
                    }
                }

                // this kind of route require one more check.
                if (sitedb != null && repo != null && nameorid != null)
                {
                    var siteobj = repo.GetByNameOrId(nameorid);
                    if (siteobj == null)
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }


            if (sysRoute.Name != null)
            {
                return(sysRoute);
            }

            return(null);
        }
示例#29
0
        public void SyncToDb(string FullPath, SiteDb SiteDb, byte[] diskbytes = null)
        {
            if (diskbytes == null)
            {
                diskbytes = this.ReadAllBytes(FullPath);
            }
            if (diskbytes == null)
            {
                return;
            }

            string OldRelativeUrl = null;
            string RelativeUrl    = null;

            IRepository repo   = null;
            ISiteObject result = null;

            Routing.Route route        = null;
            string        NameFromFile = null;
            string        extension    = UrlHelper.FileExtension(FullPath);

            if (!string.IsNullOrEmpty(extension) && !extension.StartsWith("."))
            {
                extension = "." + extension;
            }
            if (!string.IsNullOrEmpty(extension))
            {
                extension = extension.ToLower();
            }

            var NonRoutable = DiskPathService.GetNonRoutableObject(FullPath);

            if (NonRoutable != null)
            {
                repo         = SiteDb.GetRepository(NonRoutable.StoreName);
                NameFromFile = NonRoutable.Name;
                string name = string.IsNullOrWhiteSpace(NonRoutable.Name) ? NonRoutable.Id.ToString() : NonRoutable.Name;
                if (!string.IsNullOrEmpty(NonRoutable.Extension))
                {
                    extension = NonRoutable.Extension.ToLower();
                    if (!extension.StartsWith("."))
                    {
                        extension = "." + extension;
                    }
                }

                result = repo.GetByNameOrId(name) as ISiteObject;

                if (result == null)
                {
                    if (name.ToLower().EndsWith(extension))
                    {
                        name   = name.Substring(0, name.Length - extension.Length);
                        result = repo.GetByNameOrId(name);
                    }
                    else
                    {
                        name   = name + extension;
                        result = repo.GetByNameOrId(name);
                    }
                }
            }
            else
            {
                OldRelativeUrl = DiskPathService.GetRelativeUrl(SiteDb.WebSite, FullPath);
                RelativeUrl    = Kooboo.Sites.Helper.RouteHelper.ToValidRoute(OldRelativeUrl);

                route = SiteDb.Routes.GetByUrl(RelativeUrl);
                if (route != null)
                {
                    repo   = SiteDb.GetRepository(route.DestinationConstType);
                    result = repo.Get(route.objectId) as ISiteObject;
                }
                else
                {
                    var ModelType = Service.ConstTypeService.GetModelTypeByUrl(RelativeUrl);
                    if (ModelType == null)
                    {
                        return;
                    }
                    repo = SiteDb.GetRepository(ModelType);
                }
                NameFromFile = UrlHelper.FileName(RelativeUrl);
            }

            if (result == null)
            {
                result = Activator.CreateInstance(repo.ModelType) as ISiteObject;
            }

            if (!DiskObjectConverter.FromBytes(ref result, diskbytes, SiteDb))
            {
                return;
            }

            if (result is IExtensionable)
            {
                var extensionfile = result as IExtensionable;
                extensionfile.Extension = extension;
            }

            if (string.IsNullOrEmpty(result.Name))
            {
                result.Name = Lib.Helper.StringHelper.ToValidFileName(NameFromFile);
            }

            #region "Routing"

            if (!string.IsNullOrEmpty(RelativeUrl))
            {
                SiteDb.Routes.AddOrUpdate(RelativeUrl, result as SiteObject);
            }
            else
            {
                // # Rule1, only the API is different...
                if (result is Kooboo.Sites.Models.Code)
                {
                    var code = result as Code;
                    if (code.CodeType == CodeType.Api)
                    {
                        bool shouldUpdateCodeRouteText = false;

                        var diskroute = DiskObjectConverter.GetRouteFromCodeBytes(diskbytes);
                        if (string.IsNullOrWhiteSpace(diskroute))
                        {
                            // # Rule2, Api must have a route defined, otherwise it is a new api.
                            var newroute = DiskObjectConverter.GetNewRoute(SiteDb, code.Name);
                            SiteDb.Routes.AddOrUpdate(newroute, code);
                            shouldUpdateCodeRouteText = true;
                        }
                        else
                        {
                            // # Rule 3, Check if this is its own route, or someelse routes.
                            // Own rule, do nothing.
                            var coderoute = SiteDb.Routes.Get(diskroute);

                            if (coderoute != null && coderoute.objectId != default(Guid) && coderoute.objectId != code.Id)
                            {
                                //Someone else route already. make a new one
                                diskroute = DiskObjectConverter.GetNewRoute(SiteDb, diskroute);
                                coderoute = null;
                                shouldUpdateCodeRouteText = true;
                            }

                            if (coderoute == null)
                            {
                                //#Rule 4, If route does not exists yet. Add and delte old one if any.
                                var oldroute = SiteDb.Routes.GetByObjectId(code.Id);
                                SiteDb.Routes.AddOrUpdate(diskroute, code);
                                if (oldroute != null)
                                {
                                    SiteDb.Routes.Delete(oldroute.Id);
                                }
                            }
                            else
                            {
                                // donothing.
                            }
                        }

                        if (shouldUpdateCodeRouteText)
                        {
                            this.SyncToDisk(SiteDb, code, ChangeType.Update, SiteDb.Code.StoreName);
                        }
                    }
                }
            }

            #endregion

            if (!isSameName(result.Name, NameFromFile, extension) || OldRelativeUrl != RelativeUrl)
            {
                if (File.Exists(FullPath))
                {
                    File.Delete(FullPath);
                }
                repo.AddOrUpdate(result);
            }

            else
            {
                repo.AddOrUpdate(result);
            }
        }
示例#30
0
        public Task MapAsync(Func <IContainer> container, Type type, MethodInfo method, Routing.Route route)
        {
            container.ThrowIfNull("container");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            route.ThrowIfNull("route");

            bool methodReturnTypeImplementsIResponse = method.ReturnType.ImplementsInterface <IResponse>();
            bool methodReturnTypeIsTaskT             = method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task <>);
            bool methodReturnTypeIsVoid = method.ReturnType == typeof(void);

            if (methodReturnTypeImplementsIResponse)
            {
                ParameterInfo[]     parameterInfos = method.GetParameters();
                ParameterExpression instanceParameterExpression   = Expression.Parameter(typeof(object), "instance");
                ParameterExpression parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                UnaryExpression     unaryExpression =
                    Expression.Convert(
                        Expression.Call(
                            Expression.Convert(instanceParameterExpression, type),
                            method,
                            parameterInfos.Select((arg, index) => Expression.Convert(
                                                      Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                                                      arg.ParameterType))),
                        typeof(IResponse));
                Func <object, object[], IResponse> @delegate = Expression.Lambda <Func <object, object[], IResponse> >(unaryExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWith(
                    async context =>
                {
                    object instance;

                    try
                    {
                        instance = container().GetInstance(type);
                    }
                    catch (Exception exception)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                    }
                    if (instance == null)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                    }

                    var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                    object[] parameterValues    = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();

                    return(@delegate(instance, parameterValues));
                },
                    method.ReturnType);
            }
            else if (methodReturnTypeIsTaskT)
            {
                ParameterInfo[]     parameterInfos = method.GetParameters();
                ParameterExpression instanceParameterExpression   = Expression.Parameter(typeof(object), "instance");
                ParameterExpression parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                Type       methodGenericArgumentType = method.ReturnType.GetGenericArguments()[0];
                MethodInfo upcastMethodInfo          = typeof(TaskExtensions)
                                                       .GetMethod("Upcast", BindingFlags.Static | BindingFlags.Public)
                                                       .MakeGenericMethod(methodGenericArgumentType, typeof(IResponse));
                UnaryExpression unaryExpression =
                    Expression.Convert(
                        Expression.Call(
                            upcastMethodInfo,
                            Expression.Call(
                                Expression.Convert(instanceParameterExpression, type),
                                method,
                                parameterInfos.Select((arg, index) => Expression.Convert(
                                                          Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                                                          arg.ParameterType)))),
                        upcastMethodInfo.ReturnType);
                Func <object, object[], Task <IResponse> > @delegate = Expression.Lambda <Func <object, object[], Task <IResponse> > >(unaryExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWith(
                    async context =>
                {
                    object instance;

                    try
                    {
                        instance = container().GetInstance(type);
                    }
                    catch (Exception exception)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                    }
                    if (instance == null)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                    }

                    var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                    object[] parameterValues    = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();

                    return(await @delegate(instance, parameterValues));
                },
                    methodGenericArgumentType);
            }
            else if (methodReturnTypeIsVoid)
            {
                ParameterInfo[]      parameterInfos = method.GetParameters();
                ParameterExpression  instanceParameterExpression   = Expression.Parameter(typeof(object), "instance");
                ParameterExpression  parametersParameterExpression = Expression.Parameter(typeof(object[]), "parameters");
                MethodCallExpression methodCallExpression          =
                    Expression.Call(
                        Expression.Convert(instanceParameterExpression, type),
                        method,
                        parameterInfos.Select((arg, index) => Expression.Convert(
                                                  Expression.ArrayIndex(parametersParameterExpression, Expression.Constant(index)),
                                                  arg.ParameterType)));
                Action <object, object[]> @delegate = Expression.Lambda <Action <object, object[]> >(methodCallExpression, instanceParameterExpression, parametersParameterExpression).Compile();

                route.RespondWithNoContent(
                    async context =>
                {
                    object instance;

                    try
                    {
                        instance = container().GetInstance(type);
                    }
                    catch (Exception exception)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName), exception);
                    }
                    if (instance == null)
                    {
                        throw new ApplicationException(String.Format("Unable to resolve instance of type {0}.", type.FullName));
                    }

                    var parameterValueRetriever = new ParameterValueRetriever(_parameterMappers);
                    object[] parameterValues    = (await parameterValueRetriever.GetParameterValuesAsync(context, type, method)).ToArray();

                    @delegate(instance, parameterValues);
                });
            }
            else
            {
                throw new ApplicationException(String.Format("The return type of {0}.{1} must implement {2} or be a {3} whose generic type argument implements {2}.", type.FullName, method.Name, typeof(IResponse).Name, typeof(Task <>)));
            }

            return(Task.Factory.Empty());
        }
示例#31
0
文件: Route.cs 项目: joongonn/mHttp
 internal EndpointBuilder(Method method, string route)
 {
     Method = method;
     Route = new Routing.Route(route);
 }