Esempio n. 1
0
        internal static void AddToCache <T>(T obj)
        {
            lock (_cache)
            {
                RouteCache tc = new RouteCache {
                    Items = new List <RouteCacheItem>()
                };

                Type cls   = obj.GetType();
                var  paths = cls.GetCustomAttributesFromInterfaces <RestBasePath>().ToList();

                if (paths.Count > 0)
                {
                    tc.ModulePath = paths[0].BasePath;
                }
                _cache.Add(cls, tc);

                foreach (MethodInfo m in cls.GetMethods())
                {
                    Rest r = m.GetCustomAttributesFromInterfaces <Rest>().FirstOrDefault();
                    if (r == null)
                    {
                        continue;
                    }

                    Type[]     types  = m.GetParameters().Select(a => a.ParameterType).ToArray();
                    MethodInfo method = cls.GetInterfaces().FirstOrDefault(a => a.GetMethod(m.Name, types) != null)?.GetMethod(m.Name, types);
                    if (method == null)
                    {
                        method = m;
                    }
                    (string err, List <ParamInfo> @params)result = CheckMethodAssign(method, r);

                    RouteCacheItem c = new RouteCacheItem
                    {
                        Verb        = r.Verb,
                        Route       = r.Route,
                        IsAsync     = method.IsAsyncMethod(),
                        MethodInfo  = method,
                        ContentType = r.ResponseContentType,
                        Parameters  = result.Item2
                    };
                    tc.Items.Add(c);
                }

                _cache.Add(cls, tc);
            }
        }
Esempio n. 2
0
        public MatchedRouteDto(RouteCacheItem r)
        {
            Id            = r.Id;
            DepotId       = r.DepotId;
            RouteName     = r.RouteName;
            MainVehicleCn = r.VehicleCn;

            if (!r.AltVehicleId.HasValue)
            {
                VehicleCn      = r.VehicleCn;
                VehicleLicense = r.VehicleLicense;
            }
            else
            {
                VehicleCn      = r.AltVehicleCn;
                VehicleLicense = r.AltVehicleLicense;
            }
        }
Esempio n. 3
0
        public (RouteCacheItem, RouteWorkerCacheItem) GetRouteWorker(DateTime carryoutDate, int depotId, int workerId)
        {
            var list = Get(carryoutDate, depotId);

            if (list.Count == 0)
            {
                return(null, null);
            }

            RouteCacheItem a = null;

            foreach (var route in (List <RouteCacheItem>)list)
            {
                a = route;
                foreach (var worker in route.Workers)
                {
                    if (worker.WorkerId == workerId)
                    {
                        return(route, worker);
                    }
                }
            }
            return(a, null);
        }
Esempio n. 4
0
        public static IRouteBuilder RouteFor(this IRouteBuilder builder, IHttpContextAccessor obj)
        {
            string ModulePath = "";

            Type cls   = obj.GetType();
            var  paths = cls.GetCustomAttributesFromInterfaces <RestBasePath>().ToList();

            if (paths.Count > 0)
            {
                ModulePath = paths[0].BasePath;
            }


            foreach (MethodInfo m in cls.GetMethods())
            {
                Rest r = m.GetCustomAttributesFromInterfaces <Rest>().FirstOrDefault();
                if (r == null)
                {
                    continue;
                }

                Type[]     types  = m.GetParameters().Select(a => a.ParameterType).ToArray();
                MethodInfo method = cls.GetInterfaces().FirstOrDefault(a => a.GetMethod(m.Name, types) != null)?.GetMethod(m.Name, types);
                if (method == null)
                {
                    method = m;
                }
                (string err, List <ParamInfo> @params)result = CheckMethodAssign(method, r);

                RouteCacheItem c = new RouteCacheItem
                {
                    Verb        = r.Verb,
                    Route       = r.Route,
                    IsAsync     = method.IsAsyncMethod(),
                    MethodInfo  = method,
                    ContentType = r.ResponseContentType,
                    Parameters  = result.@params
                };
                string path = ModulePath + (ModulePath[ModulePath.Length - 1] == '/' || r.Route[0] == '/' ? "" : "/") + r.Route;

                builder.MapVerb(r.Verb.ToString(), path, async(request, response, routeData) =>
                {
                    obj.HttpContext = request.HttpContext;

                    List <object> paramList = new List <object>();

                    bool bodyprocessed = false;
                    foreach (var param in method.GetParameters())
                    {
                        string val = "";
                        object o;
                        if (routeData.Values.ContainsKey(param.Name))
                        {
                            val = routeData.Values[param.Name].ToString();
                        }
                        else if (request.Query.ContainsKey(param.Name))
                        {
                            val = request.Query[param.Name].FirstOrDefault();
                        }
                        else if (request.HasFormContentType && request.Form.ContainsKey(param.Name))
                        {
                            val = request.Form[param.Name].FirstOrDefault();
                        }
                        else if (param.HasDefaultValue)
                        {
                            paramList.Add(param.DefaultValue);
                            continue;
                        }

                        if (param.ParameterType == typeof(int) || param.ParameterType == typeof(Int32))
                        {
                            if (int.TryParse(val, out int i))
                            {
                                o = i;
                            }
                            else if (param.HasDefaultValue)
                            {
                                o = param.DefaultValue;
                            }
                            else
                            {
                                throw new Exception($"{param.Name} failed to parse");
                            }
                        }
                        else if (param.ParameterType == typeof(float))
                        {
                            if (float.TryParse(val, out float f))
                            {
                                o = f;
                            }
                            else if (param.HasDefaultValue)
                            {
                                o = param.DefaultValue;
                            }
                            else
                            {
                                throw new Exception($"{param.Name} failed to parse");
                            }
                        }
                        else if (param.ParameterType == typeof(string))
                        {
                            o = val;
                        }
                        else if (param.ParameterType == typeof(DateTime))
                        {
                            if (DateTime.TryParse(val, out DateTime f))
                            {
                                o = f;
                            }
                            else if (param.HasDefaultValue)
                            {
                                o = param.DefaultValue;
                            }
                            else
                            {
                                throw new Exception($"{param.Name} failed to parse");
                            }
                        }
                        else if (request.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                        {
                            using (StreamReader reader = new StreamReader(request.Body))
                            {
                                bodyprocessed = true;
                                o             = JsonConvert.DeserializeObject(reader.ReadToEnd(), param.ParameterType);
                            }
                        }
                        else
                        {
                            throw new Exception($"{param.ParameterType} is not known to be parsed!");
                        }

                        paramList.Add(o);
                    }

                    var invocation = method.Invoke(obj, paramList.ToArray());

                    if (invocation is ActionResult <object> action)
                    {
                        await action.Result.ExecuteResultAsync(new ActionContext(request.HttpContext, routeData, new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()));
                        invocation = action.Value;
                    }

                    if (invocation is ActionResult act)
                    {
                        await act.ExecuteResultAsync(new ActionContext(request.HttpContext, routeData, new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()));
                        return;
                    }

                    if (invocation is StreamWithResponse respStr)
                    {
                        response.ContentType   = respStr.ContentType;
                        response.ContentLength = respStr.ContentLength;
                        response.StatusCode    = (int)respStr.ResponseStatus;

                        foreach (var pair in respStr.Headers)
                        {
                            response.Headers[pair.Key] = pair.Value;
                        }

                        if (respStr.HasContent)
                        {
                            response.Body = respStr.Stream;
                            return;
                        }
                    }

                    switch (request.Headers["accept"].FirstOrDefault()?.ToLower())
                    {
                    case "application/xml":
                        await response.WriteAsync(invocation.XmlSerializeObject());
                        break;

                    default:
                        await response.WriteAsync(JsonConvert.SerializeObject(invocation));
                        break;
                    }
                });
            }

            return(builder);
        }