コード例 #1
0
 public override void Update()
 {
     if (Emulator != null)
     {
         APIs = InitApiHawkContainerInstance(Emulator.ServiceProvider, (string message) => throw new Exception(message));
     }
 }
コード例 #2
0
        private static void OnContainerSuccess(ApiContainer container)
        {
            if (container == null)
            {
                return;
            }

            ApiModelListContainer <APIUser> listContainer = container.TryCast <ApiModelListContainer <APIUser> >();

            if (listContainer != null)
            {
                try
                {
                    for (int i = 0; i < listContainer.ResponseList.Count; i++)
                    {
                        cachedUsers[listContainer.ResponseModels.get_Item(i).id] = new UserInfoExtensionsAPIUser(listContainer.ResponseList.get_Item(i));
                    }
                }
                catch (Exception ex)
                {
                    MelonLogger.Error("Failed while caching user from list:\n" + ex.ToString());
                }
            }
            else if (container.Model != null && container.Model.GetIl2CppType() == Il2CppType.Of <APIUser>())
            {
                try
                {
                    cachedUsers[container.Model.id] = new UserInfoExtensionsAPIUser(container.Data);
                }
                catch (Exception ex)
                {
                    MelonLogger.Error("Failed while caching user:\n" + ex.ToString());
                }
            }
        }
コード例 #3
0
ファイル: HttpRouteHandler.cs プロジェクト: daview/blqw.MIS
        public HttpRouteHandler(string urlTemplate)
        {
            var container = new ApiContainer("Mvc5", ExportedTypes.Enumerable());
            var entry     = new ServiceEntry(container, urlTemplate);

            _scheduler = Scheduler.Create(entry);
        }
コード例 #4
0
ファイル: ServiceEntry.cs プロジェクト: daview/blqw.MIS
 public ServiceEntry(ApiContainer container)
 {
     Container = container ?? throw new ArgumentNullException(nameof(container));
     Invoker   = new DefaultInvoker();
     Resolver  = new Resolver();
     Selector  = new Selector(container);
 }
コード例 #5
0
 /// <summary>
 /// 实例化命名空间
 /// </summary>
 /// <param name="namespace">命名空间完整名称</param>
 /// <param name="container">API容器</param>
 public NamespaceDescriptor(string @namespace, ApiContainer container)
 {
     FullName  = @namespace ?? throw new ArgumentNullException(nameof(@namespace));
     Container = container ?? throw new ArgumentNullException(nameof(container));
     Name      = @namespace.Split('.').Last();
     Settings  = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
     _types    = new List <ApiClassDescriptor>();
     Types     = new ReadOnlyCollection <ApiClassDescriptor>(_types);
 }
コード例 #6
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            //设置AutoFac解析器
            System.Web.Http.Dependencies.IDependencyResolver autoFacResolver = ApiContainer.Init(); //初始化容器
            HttpConfiguration config = GlobalConfiguration.Configuration;                           //获取HttpConfiguration

            config.DependencyResolver = autoFacResolver;                                            //将AutoFac解析器设置为系统DI解析器
        }
コード例 #7
0
ファイル: ApiClassDescriptor.cs プロジェクト: daview/blqw.MIS
 /// <summary>
 /// API类初始化
 /// </summary>
 /// <param name="type">API类型对应的<see cref="Type"/></param>
 /// <param name="container">API容器</param>
 /// <param name="settings">API设置</param>
 private ApiClassDescriptor(Type type, ApiContainer container, IDictionary <string, object> settings)
 {
     Type       = type ?? throw new ArgumentNullException(nameof(type));
     Container  = container ?? throw new ArgumentNullException(nameof(container));
     Settings   = settings ?? throw new ArgumentNullException(nameof(settings));
     Apis       = new ReadOnlyCollection <ApiDescriptor>(_apis = new List <ApiDescriptor>());
     Properties = new ReadOnlyCollection <ApiPropertyDescriptor>(_properties = new List <ApiPropertyDescriptor>());
     Name       = type.Name;
     FullName   = GetFullName(type);
 }
コード例 #8
0
ファイル: Selector.cs プロジェクト: daview/blqw.MIS
 public Selector(ApiContainer container, string urlTemplate)
 {
     if (urlTemplate == null)
     {
         throw new ArgumentNullException(nameof(urlTemplate));
     }
     _urlTemplate = urlTemplate.ToLowerInvariant();
     _container   = container ?? throw new ArgumentNullException(nameof(container));
     Data         = new NameDictionary();
 }
コード例 #9
0
        private static void ProcessVariable(ApiContainer apiContainer, XmlNode memberNode, string namespaceName, bool isClassMember)
        {
            NamedElement namedElement = GetNamedElement(memberNode);

            if (namedElement != null)
            {
                apiContainer.Variables.Add(new Variable(namespaceName, namedElement.Name, namedElement.Type,
                                                        namedElement.TypeInfo, Xml.GetIsStatic(memberNode), isClassMember, namedElement.IsConstant, namedElement.IsReference,
                                                        namedElement.IsRawPointer, namedElement.IsSharedPointer, namedElement.IsUniquePointer));
            }
        }
コード例 #10
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services
            .AddMvc(MvcServiceSetup).
            AddJsonOptions(options =>
            {
                options.SerializerSettings.Formatting = Formatting.Indented;
            });

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Audience     = Configuration[AppConfigConsts.TokenAudience];
                options.ClaimsIssuer = Configuration[AppConfigConsts.TokenIssuer];
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration[AppConfigConsts.TokenIssuer],
                    ValidAudience    = Configuration[AppConfigConsts.TokenAudience],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration[AppConfigConsts.TokenKey]))
                };
            });

            services.AddApiVersioning(o => o.ReportApiVersions = true);

            services.AddMvc().AddFluentValidation();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "Microservice", Version = "v1"
                });
                options.CustomSchemaIds(x => x.FullName);
                options.DescribeAllEnumsAsStrings();
                options.AddSecurityDefinition("Authentication", new ApiKeyScheme {
                    Description = "Authorization Token", Name = "Authorization", In = "header", Type = "apiKey"
                });

                this.SwaggerServiceSetup(options);
            });

            services.AddAutoMapper(this.AutoMapperServiceSetup);

            var dependencyContainer = new ApiContainer(Configuration, this.HostingEnvironment.EnvironmentName);

            dependencyContainer.Container.Populate(services);

            return(dependencyContainer.Container.GetInstance <IServiceProvider>());
        }
コード例 #11
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Get your HttpConfiguration.
            HttpConfiguration config = GlobalConfiguration.Configuration;

            ApiContainer.Init(config);
        }
コード例 #12
0
        private static void AvatarPedestalPatch(ApiContainer __0)
        {
            if (__0.Error != null || __0.Code != 200)
            {
                return;
            }
            var model = __0.Model?.TryCast <ApiAvatar>();

            if (model == null)
            {
                return;
            }

            Database?.UpdateStoredAvatar(model);
        }
コード例 #13
0
ファイル: MISMiddleware.cs プロジェクト: daview/blqw.MIS
        public MISMiddleware(OwinMiddleware next)
            : base(next)
        {
            var container = new ApiContainer("Owin", ExportedTypes.Enumerable());
            var entry     = new ServiceEntry(container);

            _scheduler = new Scheduler(entry);
            var urls = ((Selector)entry.Selector).GetAllUrls().ToArray();

            foreach (var url in urls)
            {
                Console.WriteLine(url);
            }
            Console.WriteLine($"载入接口完成,共 {urls.Length} 个");
        }
コード例 #14
0
        private static void ProcessFunction(ApiContainer apiContainer, XmlNode memberNode, string namespaceName, bool isClassMember)
        {
            List <NamedElement> parameters = new List <NamedElement>();

            foreach (XmlNode parameterNode in memberNode.SelectNodes(Xml.Param))
            {
                parameters.Add(GetNamedElement(parameterNode));
            }

            Element returnType    = GetElement(memberNode);
            string  name          = Xml.GetName(memberNode);
            bool    isConstructor = apiContainer is Class classDefinition && classDefinition.Name == name;

            apiContainer.Functions.Add(new Function(Xml.GetId(memberNode), namespaceName, name, returnType, Xml.GetIsConstant(memberNode), isConstructor, Xml.GetIsStatic(memberNode), isClassMember, parameters.AsReadOnly()));
        }
コード例 #15
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //初始化容器,并返回适用于WebApi的AutoFac解析器
            System.Web.Http.Dependencies.IDependencyResolver autoFacResolver = ApiContainer.Init();
            //获取HttpConfiguration
            HttpConfiguration config = GlobalConfiguration.Configuration;

            //将AutoFac解析器设置为系统DI解析器
            config.DependencyResolver = autoFacResolver;
        }
コード例 #16
0
        private static void OnContainerComplete(ApiContainer __2)
        {
            if (__2 == null)
            {
                return;
            }

            if (__2.OnSuccess != null)
            {
                __2.OnSuccess = ((Il2CppSystem.Action <ApiContainer>) new Action <ApiContainer>(OnContainerSuccess)).CombineImpl(__2.OnSuccess).Cast <Il2CppSystem.Action <ApiContainer> >();
            }
            else
            {
                __2.OnSuccess = new Action <ApiContainer>(OnContainerSuccess);
            }
        }
コード例 #17
0
        public IActionResult GetCoursesForPagination(PaginationData data)
        {
            int page = data.RequestPage ?? 0;

            _pageSize = data.PageLimit ?? 4;
            var itemsToSkip =
                page == 0 ? 0 : (page - 1) * _pageSize;

            var container = new ApiContainer();


            var filter = new CourseFilter()
            {
                Category        = data.Category,
                UserSearchInput = data.UserSearchInput
            };
            var courses = _data.GetCourses(filter).OrderBy(t => t.Id).Skip(itemsToSkip).Take(_pageSize);

            if (!courses.Any())
            {
                return(NotFound());
            }

            var dataRez = new List <CourseDto>();
            var model   = courses.Select(c => _mapper.Map <Course, CourseDto>(c));

            foreach (var course in courses)
            {
                var dtoModel = _mapper.Map <Course, CourseDto>(course);
                dtoModel.StudentCount = course.Users.Count();
                dtoModel.UserRaiting  = 5;
                dtoModel.Author       =
                    string.IsNullOrEmpty(course.Author.Name) || string.IsNullOrEmpty(course.Author.Surname)
                        ? course.Author.UserName
                        : $"{course.Author.Name} {course.Author.Surname}";
                dataRez.Add(dtoModel);
            }
            container.Data        = dataRez;
            container.CurrentPage = page;
            container.TotalRecord = _data.GetCourses(filter).Count();
            container.PageLimit   = _pageSize;
            container.Fetched     = courses.Count();
            return(Ok(container));
        }
コード例 #18
0
ファイル: FavCatMod.cs プロジェクト: knah/VRCMods
        private static void AvatarPedestalPatch(ApiContainer __0)
        {
            if (__0.Code != 200)
            {
                return;
            }
            var model = __0.Model?.TryCast <ApiAvatar>();

            if (model == null)
            {
                return;
            }

            if (MelonDebug.IsEnabled())
            {
                MelonDebug.Msg($"Ingested avatar with ID={model.id}");
            }
            Database?.UpdateStoredAvatar(model);
        }
コード例 #19
0
        private static void ProcessMembers(ApiContainer apiContainer, XmlNode node, string namespaceName)
        {
            bool isClassMember = apiContainer is Class;

            foreach (XmlNode memberNode in GetMemberNodes(node))
            {
                switch (Xml.GetKind(memberNode))
                {
                case Xml.Function:
                    ProcessFunction(apiContainer, memberNode, namespaceName, isClassMember);
                    break;

                case Xml.Variable:
                    ProcessVariable(apiContainer, memberNode, namespaceName, isClassMember);
                    break;

                default:
                    // This can only happen if GetMemberNodes is broken.
                    throw new System.InvalidOperationException("Member nodes must have type 'Epoxy.Api.Xml.Function' or 'Epoxy.Api.Xml.Variable'.");
                }
            }
        }
コード例 #20
0
ファイル: ApiClassDescriptor.cs プロジェクト: daview/blqw.MIS
        /// <summary>
        /// 构建一个ApiClass描述,如果<paramref name="type"/>不是ApiClass则返回null
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static ApiClassDescriptor Create(Type type, ApiContainer container)
        {
            var typeInfo = type.GetTypeInfo();

            if (!typeInfo.IsClass || typeInfo.IsAbstract || typeInfo.IsGenericTypeDefinition) //排除抽象类和泛型定义类型
            {
                return(null);
            }

            if (typeInfo.DeclaredMethods.Any(m => m.IsDefined(typeof(ApiAttribute))) == false)
            {
                return(null);
            }

            var classAttrs = typeInfo.GetCustomAttributes <ApiClassAttribute>().ToArray();

            var settings = container.Provider.ParseSetting(classAttrs) ?? new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            var apiclass = new ApiClassDescriptor(type, container, settings);

            var propAttrs = typeInfo.DeclaredProperties
                            .Select(it => ApiPropertyDescriptor.Create(it, apiclass))
                            .Where(it => it != null);

            apiclass._properties.AddRange(propAttrs);

            var apis = typeInfo.DeclaredMethods
                       .Select(it => ApiDescriptor.Create(it, apiclass))
                       .Where(it => it != null);

            apiclass._apis.AddRange(apis);

            if (classAttrs.Length == 0 && apiclass._properties.Count == 0 && apiclass._apis.Count == 0)
            {
                return(null);
            }

            return(apiclass);
        }
コード例 #21
0
 internal static void ApiAvatarFailed(ApiContainer apiContainer)
 {
 }
コード例 #22
0
 protected IRepository <T> ResolveContextLocator <T>(object target) where T : class
 {
     return(ApiContainer.Resolve <IRepository <T> >(new NamedParameter("target", target)));
 }
コード例 #23
0
 public Selector(ApiContainer container)
 {
     _container = container ?? throw new ArgumentNullException(nameof(container));
     Data       = new NameDictionary();
     _route     = new RouteTable(_container.Apis);
 }
コード例 #24
0
 internal static void ApiAvatarRecieved(ApiContainer apiContainer)
 {
 }
コード例 #25
0
        public static void FetchFavList(string endpoint, HTTPMethods method, ApiContainer responseContainer = null, Dictionary <string, object> requestParams = null, bool needsAPIKey = true, bool authenticationRequired = true, bool disableCache = false, float cacheLifetime = 3600f)
        {
            string text = (!disableCache) ? "cyan" : "red";

            VRC.Core.Logger.Log(string.Concat(new object[]
            {
                "<color=",
                text,
                ">Dispatch ",
                method,
                " ",
                endpoint,
                (requestParams == null) ? string.Empty : (" params: " + Json.Encode(requestParams)),
                " disableCache: ",
                disableCache.ToString(),
                "</color>"
            }), DebugLevel.API);

            MethodInfo UpdateDelegatorMethod = typeof(API).Assembly.GetType("VRC.Core.UpdateDelegator").GetMethod(
                "Dispatch",
                BindingFlags.Static | BindingFlags.Public,
                null,
                new Type[] { typeof(Action) },
                null
                );
            Action delegateAction = delegate
            {
                MethodInfo SendRequestInternalMethod = typeof(API).GetMethod(
                    "SendRequestInternal",
                    BindingFlags.Static | BindingFlags.NonPublic,
                    null,
                    new Type[] { typeof(string), typeof(HTTPMethods), typeof(ApiContainer), typeof(Dictionary <string, object>), typeof(bool), typeof(bool), typeof(bool), typeof(float) },
                    null
                    );
                if (endpoint == "avatars" && requestParams.ContainsKey("user") && requestParams["user"] == "me")
                {
                    ApiModelListContainer <ApiAvatar> rc = new ApiModelListContainer <ApiAvatar>
                    {
                        OnSuccess = delegate(ApiContainer c)
                        {
                            Thread t = new Thread(new ThreadStart(() => {
                                List <object> avatarsFav = VRCTServerManager.GetAvatars();

                                ((List <object>)c.Data).AddRange(avatarsFav);


                                MethodInfo SetResponseModelsMethod = typeof(ApiModelListContainer <ApiAvatar>).GetMethod(
                                    "set_ResponseModels",
                                    BindingFlags.Instance | BindingFlags.NonPublic,
                                    null,
                                    new Type[] { typeof(List <ApiAvatar>) },
                                    null
                                    );

                                String responseError = "";

                                SetResponseModelsMethod.Invoke(c, new object[] { API.ConvertJsonListToModelList <ApiAvatar>((List <object>)c.Data, ref responseError, c.DataTimestamp) });


                                lock (cb)
                                {
                                    cb.Add(
                                        new Action(() => {
                                        responseContainer.OnSuccess(c);
                                    })
                                        );
                                }
                            }));
                            t.Start();
                        },
                        OnError = delegate(ApiContainer c)
                        {
                            responseContainer.OnError(c);
                        }
                    };
                    SendRequestInternalMethod.Invoke(null, new object[] { endpoint, method, rc, requestParams, needsAPIKey, authenticationRequired, disableCache, cacheLifetime });
                }
                else
                {
                    SendRequestInternalMethod.Invoke(null, new object[] { endpoint, method, responseContainer, requestParams, needsAPIKey, authenticationRequired, disableCache, cacheLifetime });
                }
            };

            UpdateDelegatorMethod.Invoke(null, new object[] { delegateAction });
        }