コード例 #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="longpolling">Set true for event notification, false for immediate response.</param>
 /// <returns></returns>
 public async Task<Event> GetEventAsync(bool longpolling, ApiVersion version = ApiVersion.V1_0
     , CancellationTokenSource cancel = null)
 {
     return await Single<Event>(
         RequestGenerator.Jsonize("getEvent", version, longpolling),
         CustomParser.AsCameraEvent, cancel).ConfigureAwait(false);
 }
コード例 #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="longpolling">Set true for event notification, false for immediate response.</param>
 /// <returns></returns>
 public Task<Event> GetEventAsync(bool longpolling, ApiVersion version = ApiVersion.V1_0
     , CancellationTokenSource cancel = null)
 {
     return Single(
         RequestGenerator.Jsonize("getEvent", version, longpolling),
         CustomParser.AsCameraEvent, cancel);
 }
コード例 #3
0
ファイル: BeatRequest.cs プロジェクト: mingkongbin/anycmd
 public BeatRequest(ApiVersion version)
 {
     if (version == ApiVersion.Undefined || version == default(ApiVersion))
     {
         throw new AnycmdException("非法的协议版本号" + version.ToName());
     }
     this.Version = version.ToName();
 }
コード例 #4
0
ファイル: GroupmeApi.cs プロジェクト: legendz3/GroupMeBot
        public GroupmeApi(ApiVersion version)
        {
            string v3Url = ConfigurationManager.AppSettings.Get("V3_Url");
            string v2Url = ConfigurationManager.AppSettings.Get("V2_Url");
            _v3Client = new RestClient(v3Url);
            _v2Client = new RestClient(v2Url);

            _defaultClient = GeClientByVersion(version);
            _token = ConfigurationManager.AppSettings.Get("token");
        }
        /// <summary>
        /// Registers a pair of API version and a <see cref="HttpControllerDescriptor"/>
        /// </summary>
        /// <param name="apiVersion"></param>
        /// <param name="controllerDescriptor"></param>
        internal void AddVersion(ApiVersion apiVersion, HttpControllerDescriptor controllerDescriptor) {
            if (apiVersion == null) {
                throw new ArgumentNullException("apiVersion");
            }
            if (controllerDescriptor == null) {
                throw new ArgumentNullException("controllerDescriptor");
            }

            try {
                this._descriptorsPerVersion.Add(apiVersion, controllerDescriptor);
            }
            catch (ArgumentException ex) {
                throw new ArgumentException(ExceptionResources.ApiVersionAlreadyAdded, "apiVersion", ex);
            }
        }
コード例 #6
0
 private static string ToString(ApiVersion version)
 {
     switch (version)
     {
         case ApiVersion.V1_0:
             return "1.0";
         case ApiVersion.V1_1:
             return "1.1";
         case ApiVersion.V1_2:
             return "1.2";
         case ApiVersion.V1_3:
             return "1.3";
         default:
             throw new InvalidOperationException("Version " + version + " is not supported.");
     }
 }
コード例 #7
0
        public void IsCompatibleTest()
        {
            // executing version 3.0.0.0, accepting connections from 2.0.0.0
            var av = new ApiVersion(new Version(3, 0, 0, 0), new Version(2, 0, 0, 0));

            // server version 1.0.0.0 is not compatible (too old)
            Assert.IsFalse(av.IsCompatibleWith(new Version(1, 0, 0, 0)));

            // server version 2.0.0.0 or 3.0.0.0 is compatible
            Assert.IsTrue(av.IsCompatibleWith(new Version(2, 0, 0, 0)));
            Assert.IsTrue(av.IsCompatibleWith(new Version(3, 0, 0, 0)));

            // server version 4.0.0.0 is not compatible (too recent)
            Assert.IsFalse(av.IsCompatibleWith(new Version(4, 0, 0, 0)));

            // but can declare it is, indeed, compatible with version 2.0.0.0 or 3.0.0.0
            Assert.IsTrue(av.IsCompatibleWith(new Version(4, 0, 0, 0), new Version(2, 0, 0, 0)));
            Assert.IsTrue(av.IsCompatibleWith(new Version(4, 0, 0, 0), new Version(3, 0, 0, 0)));

            // but...
            Assert.IsFalse(av.IsCompatibleWith(new Version(4, 0, 0, 0), new Version(3, 0, 0, 1)));
        }
コード例 #8
0
 private static NGitLab.Impl.Api.ApiVersion VsApiVersionToNgitLabversion(ApiVersion apiVersion)
 {
     return((NGitLab.Impl.Api.ApiVersion)Enum.Parse(typeof(NGitLab.Impl.Api.ApiVersion), apiVersion.ToString()));
 }
コード例 #9
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <returns>
 /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
 /// </returns>
 /// <param name="other">An object to compare with this object.</param>
 public override bool Equals(ApiVersion other) {
     return other is SemVerApiVersion && ((SemVerApiVersion) other)._version == this._version;
 }
コード例 #10
0
        public User LoginAsync(bool enable2fa, string host, string email, string password, ApiVersion apiVersion)
        {
            NGitLab.GitLabClient client = null;
            User user = null;

            NGitLab.Impl.Api.ApiVersion _apiVersion = VsApiVersionToNgitLabversion(apiVersion);
            if (enable2fa)
            {
                client = NGitLab.GitLabClient.Connect(host, password, _apiVersion);
            }
            else
            {
                client = NGitLab.GitLabClient.Connect(host, email, password, _apiVersion);
            }
            try
            {
                user = client.Users.Current();
                user.PrivateToken = client.ApiToken;
                user.ApiVersion   = apiVersion;
            }
            catch (WebException ex)
            {
                var res        = (HttpWebResponse)ex.Response;
                var statusCode = (int)res.StatusCode;

                throw ex;
            }
            catch (Exception ex1)
            {
                throw ex1;
            }
            return(user);
        }
コード例 #11
0
        /// <summary>
        /// Maps the specified OData route and the OData route attributes.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="routeName">The name of the route to map.</param>
        /// <param name="routePrefix">The prefix to add to the OData route's path template.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> associated with the model.</param>
        /// <param name="configureAction">The configuring action to add the services to the root container.</param>
        /// <returns>The added <see cref="ODataRoute"/>.</returns>
        public static ODataRoute MapVersionedODataRoute(this HttpConfiguration configuration, string routeName, string routePrefix, ApiVersion apiVersion, Action <IContainerBuilder> configureAction)
        {
            Arg.NotNull(configuration, nameof(configuration));
            Arg.NotNull(apiVersion, nameof(apiVersion));
            Contract.Ensures(Contract.Result <ODataRoute>() != null);

            object ConfigureRoutingConventions(IServiceProvider serviceProvider)
            {
                var model = serviceProvider.GetRequiredService <IEdmModel>();
                var routingConventions = EnsureConventions(ODataRoutingConventions.CreateDefault());

                model.SetAnnotationValue(model, new ApiVersionAnnotation(apiVersion));
                routingConventions.Insert(0, new VersionedAttributeRoutingConvention(routeName, configuration, apiVersion));

                return(routingConventions.ToArray());
            }

            if (!IsNullOrEmpty(routePrefix))
            {
                routePrefix = routePrefix.TrimEnd('/');
            }

            var rootContainer = configuration.CreateODataRootContainer(
                routeName,
                builder =>
            {
                builder.AddService(Singleton, typeof(IEnumerable <IODataRoutingConvention>), ConfigureRoutingConventions);
                configureAction?.Invoke(builder);
            });
            var pathHandler = rootContainer.GetRequiredService <IODataPathHandler>();

            if (pathHandler != null && pathHandler.UrlKeyDelimiter == null)
            {
                pathHandler.UrlKeyDelimiter = configuration.GetUrlKeyDelimiter();
            }

            rootContainer.InitializeAttributeRouting();

            var routeConstraint = new VersionedODataPathRouteConstraint(routeName, apiVersion);
            var route           = default(ODataRoute);
            var routes          = configuration.Routes;
            var messageHandler  = rootContainer.GetService <HttpMessageHandler>();

            if (messageHandler != null)
            {
                route = new ODataRoute(
                    routePrefix,
                    routeConstraint,
                    defaults: null,
                    constraints: null,
                    dataTokens: null,
                    handler: messageHandler);
            }
            else
            {
                var batchHandler = rootContainer.GetService <ODataBatchHandler>();

                if (batchHandler != null)
                {
                    batchHandler.ODataRouteName = routeName;
                    var batchTemplate = IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch : routePrefix + '/' + ODataRouteConstants.Batch;
                    routes.MapHttpBatchRoute(routeName + nameof(ODataRouteConstants.Batch), batchTemplate, batchHandler);
                }

                route = new ODataRoute(routePrefix, routeConstraint);
            }

            routes.Add(routeName, route);
            AddApiVersionConstraintIfNecessary(route);

            var unversionedRouteConstraint = new ODataPathRouteConstraint(routeName);
            var unversionedRoute           = new ODataRoute(routePrefix, new UnversionedODataPathRouteConstraint(unversionedRouteConstraint, apiVersion));

            AddApiVersionConstraintIfNecessary(unversionedRoute);
            configuration.Routes.Add(routeName + UnversionedRouteSuffix, unversionedRoute);

            return(route);
        }
コード例 #12
0
 /// <summary>
 /// Activates TET C# Client and all underlying routines using default values. Should be called _only_ 
 /// once when an application starts up. Calling thread will be locked during
 /// initialization.
 /// </summary>
 /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param>
 /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param>
 /// <returns>True is succesfully activated, false otherwise</returns>
 public bool Activate(ApiVersion apiVersion, ClientMode mode)
 {
     return Activate(apiVersion, mode, GazeApiManager.DEFAULT_SERVER_HOST, GazeApiManager.DEFAULT_SERVER_PORT);
 }
コード例 #13
0
ファイル: TwitterApi.cs プロジェクト: hongyue/Twitter.Net
        public TwitterApi(string consumerKey, string consumerSecret, 
                          string accessToken, string tokenSecret, ApiVersion apiVersion = ApiVersion.V1)
            : this(consumerKey, consumerSecret, accessToken, tokenSecret, TokenType.AccessToken, apiVersion)
        {

        }
コード例 #14
0
        static bool ActionIsSatisfiedBy(ActionDescriptor action, ApiVersionModel model, ApiVersion version, ICollection <ActionDescriptor> implicitMatches)
        {
            Contract.Requires(action != null);
            Contract.Requires(implicitMatches != null);

            if (model == null)
            {
                return(false);
            }

            if (action.IsMappedTo(version))
            {
                return(true);
            }

            if (action.IsImplicitlyMappedTo(version))
            {
                implicitMatches.Add(action);
            }

            return(false);
        }
コード例 #15
0
ファイル: GroupmeApi.cs プロジェクト: legendz3/GroupMeBot
 private RestClient GeClientByVersion(ApiVersion version)
 {
     RestClient client;
     switch (version)
     {
         case ApiVersion.V2:
             client = _v2Client;
             break;
         case ApiVersion.V3:
             client = _v3Client;
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
     return client;
 }
コード例 #16
0
ファイル: Startup.cs プロジェクト: BakaKiller/PluralKit
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddAuthentication("SystemToken")
            .AddScheme <SystemTokenAuthenticationHandler.Opts, SystemTokenAuthenticationHandler>("SystemToken", null);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("EditSystem", p => p.RequireAuthenticatedUser().AddRequirements(new OwnSystemRequirement()));
                options.AddPolicy("EditMember", p => p.RequireAuthenticatedUser().AddRequirements(new OwnSystemRequirement()));

                options.AddPolicy("ViewMembers", p => p.AddRequirements(new PrivacyRequirement <PKSystem>(s => s.MemberListPrivacy)));
                options.AddPolicy("ViewFront", p => p.AddRequirements(new PrivacyRequirement <PKSystem>(s => s.FrontPrivacy)));
                options.AddPolicy("ViewFrontHistory", p => p.AddRequirements(new PrivacyRequirement <PKSystem>(s => s.FrontHistoryPrivacy)));
            });
            services.AddSingleton <IAuthenticationHandler, SystemTokenAuthenticationHandler>();
            services.AddSingleton <IAuthorizationHandler, MemberOwnerHandler>();
            services.AddSingleton <IAuthorizationHandler, SystemOwnerHandler>();
            services.AddSingleton <IAuthorizationHandler, SystemPrivacyHandler>();

            services.AddControllers()
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddNewtonsoftJson();     // sorry MS, this just does *more*

            services.AddApiVersioning(c =>
            {
                c.AssumeDefaultVersionWhenUnspecified = true;
                c.DefaultApiVersion = ApiVersion.Parse("1.0");
            });

            services.AddVersionedApiExplorer(c =>
            {
                c.GroupNameFormat           = "'v'VV";
                c.DefaultApiVersion         = ApiVersion.Parse("1.0");
                c.ApiVersionParameterSource = new UrlSegmentApiVersionReader();
                c.SubstituteApiVersionInUrl = true;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1.0", new OpenApiInfo {
                    Title = "PluralKit", Version = "1.0"
                });

                c.EnableAnnotations();
                c.AddSecurityDefinition("TokenAuth",
                                        new OpenApiSecurityScheme {
                    Name = "Authorization", Type = SecuritySchemeType.ApiKey
                });

                // Exclude routes without a version, then fall back to group name matching (default behavior)
                c.DocInclusionPredicate((docName, apiDesc) =>
                {
                    if (!apiDesc.RelativePath.StartsWith("v1/"))
                    {
                        return(false);
                    }
                    return(apiDesc.GroupName == docName);
                });

                // Set the comments path for the Swagger JSON and UI.
                // https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio#customize-and-extend
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
            services.AddSwaggerGenNewtonsoftSupport();
        }
コード例 #17
0
        RequestHandler VerifyRequestedApiVersionIsNotAmbiguous(HttpContext httpContext, out ApiVersion apiVersion)
        {
            Contract.Requires(httpContext != null);

            try
            {
                apiVersion = httpContext.GetRequestedApiVersion();
            }
            catch (AmbiguousApiVersionException ex)
            {
                Logger.LogInformation(ex.Message);
                apiVersion = default(ApiVersion);
                return(new BadRequestHandler(Options.ErrorResponses, AmbiguousApiVersion, ex.Message));
            }

            return(null);
        }
コード例 #18
0
 public IntroducedInApiVersionAttribute(ApiVersion version) : base(version)
 {
 }
コード例 #19
0
ファイル: Startup.cs プロジェクト: drony/Ark.Tools
 public override OpenApiInfo MakeInfo(ApiVersion version)
 => new OpenApiInfo
 {
     Title   = "API",
     Version = version.ToString("VVVV"),
 };
コード例 #20
0
        /// <summary>
        /// Determines whether the action should be considered.
        /// </summary>
        /// <param name="actionRouteParameterValue">The action route parameter value.</param>
        /// <param name="actionDescriptor">The associated <see cref="HttpActionDescriptor">action descriptor</see>.</param>
        /// <param name="route">The associated <see cref="IHttpRoute">route</see>.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to consider the controller for.</param>
        /// <returns>True if the action should be explored; otherwise, false.</returns>
        protected override bool ShouldExploreAction(string actionRouteParameterValue, HttpActionDescriptor actionDescriptor, IHttpRoute route, ApiVersion apiVersion)
        {
            Arg.NotNull(actionDescriptor, nameof(actionDescriptor));
            Arg.NotNull(route, nameof(route));
            Arg.NotNull(apiVersion, nameof(apiVersion));

            if (!(route is ODataRoute))
            {
                return(base.ShouldExploreAction(actionRouteParameterValue, actionDescriptor, route, apiVersion));
            }

            if (Options.UseApiExplorerSettings)
            {
                var setting = actionDescriptor.GetCustomAttributes <ApiExplorerSettingsAttribute>().FirstOrDefault();

                if (setting?.IgnoreApi == true)
                {
                    return(false);
                }
            }

            return(actionDescriptor.IsMappedTo(apiVersion));
        }
コード例 #21
0
ファイル: CAdapter.cs プロジェクト: Zulkir/Beholder
        public CAdapter(Direct3D direct3D, AdapterInformation adapterInfo)
        {
            this.direct3D = direct3D;
            this.adapterInfo = adapterInfo;
            desctopDisplayMode = adapterInfo.CurrentDisplayMode;
            caps = adapterInfo.GetCaps(DeviceType.Hardware);
            index = adapterInfo.Adapter;
            var shaderModel = System.Math.Min(caps.VertexShaderVersion.Major, caps.PixelShaderVersion.Major);
            apiVersion = new ApiVersion(9, (byte)shaderModel);
            var details = adapterInfo.Details;
            restrictions = new AdapterRestrictions
            {
                UniformBufferSlots = 256,
                SamplerSlots = caps.MaxSimultaneousTextures,
                ShaderResourceSlots = caps.MaxSimultaneousTextures,
                UnorderedAccessResourceSlots = 0,
                MaxVertexStreams = caps.MaxStreams,
                MaxVertexStreamElementCount = caps.MaxStreamStride / (4 * sizeof(float)),
                MaxStreamOutputTargets = 0,
                MaxViewports = 1,
                MaxRenderTargets = caps.SimultaneousRTCount,
                MaxThreadGroupsX = 0,
                MaxThreadGroupsY = 0,
                MaxThreadGroupsZ = 0,
                MaxThreadGroupsTotal = 0,
            };

            adapterDesc = new AdapterDescription
            {
                Description = details.Description,
                VendorId = details.VendorId,
                DeviceId = details.DeviceId,
                SubSysId = details.SubsystemId,
                Revision = details.Revision,
                DedicatedVideoMemory = 0,
                DedicatedSystemMemory = 0,
                SharedSystemMemory = 0,
                AdapterLuidHigh = 0,
                AdapterLuidLow = 0,
                Flags = AdapterFlags.None
            };

            outputDesc = new OutputDescription
            {
                DeviceName = details.DeviceName,
                DesctopCoordinates = new Math.Rectangle(),
                AttachedToDesctop = false,
                Rotation = ModeRotation.Unspecified,
                MonitorHandle = adapterInfo.Monitor
            };

            outputs = new[] { this };

            formatSupports = ((Format[])Enum.GetValues(typeof(Format))).ToDictionary(f => f, GetFormatSupport);
        }
コード例 #22
0
    public static void AddVersioning(this IServiceCollection services, string version)
    {
        var apiVersion = ApiVersion.Parse(version);

        AddVersioning(services, apiVersion);
    }
コード例 #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SetService"/> class.
 /// </summary>
 /// <param name="serviceAdapter">The service adapter used to interact with the MTG API.</param>
 /// <param name="version">The version of the API</param>
 public SetService(IMtgApiServiceAdapter serviceAdapter, ApiVersion version)
     : base(serviceAdapter, version, ApiEndPoint.Sets)
 {
     this._whereQueries = new NameValueCollection();
 }
コード例 #24
0
 public Activity(JsonString jsonString) : this(jsonString.ToJToken(), ApiVersion.GetLatest())
 {
 }
コード例 #25
0
        static ODataRoute MapVersionedODataRoute(
            HttpConfiguration configuration,
            string routeName,
            string routePrefix,
            IEdmModel model,
            ApiVersion apiVersion,
            IODataPathHandler pathHandler,
            IEnumerable <IODataRoutingConvention> routingConventions,
            ODataBatchHandler batchHandler,
            HttpMessageHandler defaultHandler)
        {
            Arg.NotNull(configuration, nameof(configuration));
            Arg.NotNull(model, nameof(model));
            Arg.NotNull(apiVersion, nameof(apiVersion));
            Contract.Ensures(Contract.Result <ODataRoute>() != null);

            var routeConventions = EnsureConventions(routingConventions.ToList());
            var routes           = configuration.Routes;

            if (!IsNullOrEmpty(routePrefix))
            {
                routePrefix = routePrefix.TrimEnd('/');
            }

            if (pathHandler != null && pathHandler.UrlKeyDelimiter == null)
            {
                pathHandler.UrlKeyDelimiter = configuration.GetUrlKeyDelimiter();
            }

            model.SetAnnotationValue(model, new ApiVersionAnnotation(apiVersion));
            routeConventions.Insert(0, new VersionedAttributeRoutingConvention(routeName, configuration, apiVersion));

            var rootContainer = configuration.CreateODataRootContainer(
                routeName,
                builder => builder.AddService(Singleton, typeof(IEdmModel), sp => model)
                .AddService(Singleton, typeof(IODataPathHandler), sp => pathHandler)
                .AddService(Singleton, typeof(IEnumerable <IODataRoutingConvention>), sp => routeConventions.ToArray())
                .AddService(Singleton, typeof(ODataBatchHandler), sp => batchHandler)
                .AddService(Singleton, typeof(HttpMessageHandler), sp => defaultHandler));

            rootContainer.InitializeAttributeRouting();

            var routeConstraint = new VersionedODataPathRouteConstraint(routeName, apiVersion);
            var route           = default(ODataRoute);

            if (defaultHandler != null)
            {
                route = new ODataRoute(routePrefix, routeConstraint, defaults: null, constraints: null, dataTokens: null, handler: defaultHandler);
            }
            else
            {
                if (batchHandler != null)
                {
                    batchHandler.ODataRouteName = routeName;
                    var batchTemplate = IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch : routePrefix + '/' + ODataRouteConstants.Batch;
                    routes.MapHttpBatchRoute(routeName + nameof(ODataRouteConstants.Batch), batchTemplate, batchHandler);
                }

                route = new ODataRoute(routePrefix, routeConstraint);
            }

            routes.Add(routeName, route);
            AddApiVersionConstraintIfNecessary(route);

            var unversionedRouteConstraint = new ODataPathRouteConstraint(routeName);
            var unversionedRoute           = new ODataRoute(routePrefix, new UnversionedODataPathRouteConstraint(unversionedRouteConstraint, apiVersion));

            AddApiVersionConstraintIfNecessary(unversionedRoute);
            routes.Add(routeName + UnversionedRouteSuffix, unversionedRoute);

            return(route);
        }
コード例 #26
0
 public IActionResult Get(string accountId, ApiVersion apiVersion) => Ok(new Order(GetType().FullName, accountId, apiVersion.ToString()));
コード例 #27
0
        public void OnGazeApiResponse(String response)
        {
            var reply = JsonConvert.DeserializeObject<ReplyBase>(response);

            if (reply.StatusCode == (int)HttpStatusCode.OK)
            {
                switch (reply.Category)
                {
                    case Protocol.CATEGORY_TRACKER:

                        if (reply.Request.Equals(Protocol.TRACKER_REQUEST_GET))
                        {
                            var jsreader = new JsonTextReader(new StringReader(response));
                            var json = (JObject)new JsonSerializer().Deserialize(jsreader);

                            JObject values = json[Protocol.KEY_VALUES].ToObject<JObject>();
                            JToken value;

                            if (null != values)
                            {
                                if (values.TryGetValue(Protocol.TRACKER_VERSION, out value))
                                    version = value.ToObject<ApiVersion>();

                                if (values.TryGetValue(Protocol.TRACKER_MODE_PUSH, out value))
                                {
                                    if ((bool)value)
                                        clientMode = ClientMode.Push;
                                    else
                                        clientMode = ClientMode.Pull;
                                }

                                if (values.TryGetValue(Protocol.TRACKER_HEARTBEATINTERVAL, out value))
                                    HeartbeatMillis = (int)value;

                                if (values.TryGetValue(Protocol.TRACKER_FRAMERATE, out value))
                                    Framerate = value.ToObject<FrameRate>();

                                if (values.TryGetValue(Protocol.TRACKER_TRACKERSTATE, out value))
                                {
                                    //if tracker state changed, notify listeners
                                    if ((int)value != (int)Trackerstate.GetTypeCode())
                                    {
                                        Trackerstate = (TrackerState)(int)value;

                                        lock (((ICollection)trackerStateListeners).SyncRoot)
                                        {
                                            foreach (ITrackerStateListener listener in trackerStateListeners)
                                            {
                                                try
                                                {
                                                    listener.OnTrackerStateChanged(Trackerstate);
                                                }
                                                catch (Exception e)
                                                {
                                                    Debug.WriteLine("Exception while calling ITrackerStateListener.OnTrackerStateChanged() on listener " + listener + ": " + e.StackTrace);
                                                }
                                            }
                                        }
                                    }
                                }

                                if (values.TryGetValue(Protocol.TRACKER_CALIBRATIONRESULT, out value))
                                    LastCalibrationResult = value.ToObject<CalibrationResult>();

                                if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATING, out value))
                                    IsCalibrating = (bool)value;

                                if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATED, out value))
                                {
                                    //if calibration state changed, notify listeners
                                    if ((bool)value != IsCalibrated)
                                    {
                                        IsCalibrated = (bool)value;

                                        lock (((ICollection)calibrationStateListeners).SyncRoot)
                                        {
                                            foreach (ICalibrationResultListener listener in calibrationStateListeners)
                                            {
                                                try
                                                {
                                                    listener.OnCalibrationChanged(IsCalibrated, LastCalibrationResult);
                                                }
                                                catch (Exception e)
                                                {
                                                    Debug.WriteLine("Exception while calling ICalibrationResultListener.OnCalibrationChanged() on listener " + listener + ": " + e.StackTrace);
                                                }
                                            }
                                        }
                                    }
                                }

                                if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_WIDTH, out value))
                                    ScreenResolutionWidth = (int)value;

                                if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_HEIGHT, out value))
                                    ScreenResolutionHeight = (int)value;

                                if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_WIDTH, out value))
                                    ScreenPhysicalWidth = (int)value;

                                if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_HEIGHT, out value))
                                    ScreenPhysicalHeight = (int)value;

                                if (values.TryGetValue(Protocol.TRACKER_SCREEN_INDEX, out value))
                                {
                                    //if screen index changed, notify listeners
                                    if ((int)value != ScreenIndex)
                                    {
                                        ScreenIndex = (int)value;

                                        lock (((ICollection)trackerStateListeners).SyncRoot)
                                        {
                                            foreach (ITrackerStateListener listener in trackerStateListeners)
                                            {
                                                try
                                                {
                                                    listener.OnScreenStatesChanged(ScreenIndex, ScreenResolutionWidth, ScreenResolutionHeight, ScreenPhysicalWidth, ScreenPhysicalHeight);
                                                }
                                                catch (Exception e)
                                                {
                                                    Debug.WriteLine("Exception while calling ITrackerStateListener.OnScreenStatesChanged() on listener " + listener + ": " + e.StackTrace);
                                                }
                                            }
                                        }
                                    }
                                }

                                if (values.TryGetValue(Protocol.TRACKER_FRAME, out value) && null != gazeBroadcaster)
                                {
                                    //Add gaze update to high frequency broadcasting queue
                                    lock (((ICollection)queueGazeData).SyncRoot)
                                    {
                                        queueGazeData.Enqueue(value.ToObject<GazeData>());
                                    }

                                    events.GetUpdateHandle().Set();
                                }
                            }

                            //Handle initialization
                            if (initializationLock != null)
                            {
                                lock (initializationLock)
                                {
                                    Monitor.Pulse(initializationLock);
                                    initializationLock = null;
                                }
                            }
                        }
                        else if (reply.Request.Equals(Protocol.TRACKER_REQUEST_SET))
                        {
                            //Do nothing
                        }
                        break;

                    case Protocol.CATEGORY_CALIBRATION:

                        switch (reply.Request)
                        {
                            case Protocol.CALIBRATION_REQUEST_START:

                                IsCalibrating = true;

                                if (null != calibrationListener)
                                    //Notify calibration listener that a new calibration process was successfully started
                                    try
                                    {
                                        calibrationListener.OnCalibrationStarted();
                                    }
                                    catch (Exception e)
                                    {
                                        Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationStarted() on listener " + calibrationListener + ": " + e.StackTrace);
                                    }

                                break;

                            case Protocol.CALIBRATION_REQUEST_POINTSTART:
                                break;

                            case Protocol.CALIBRATION_REQUEST_POINTEND:

                                ++sampledCalibrationPoints;

                                if (null != calibrationListener)
                                {
                                    //Notify calibration listener that a new calibration point has been sampled
                                    try
                                    {
                                        calibrationListener.OnCalibrationProgress(sampledCalibrationPoints / totalCalibrationPoints);
                                    }
                                    catch (Exception e)
                                    {
                                        Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationProgress() on listener " + calibrationListener + ": " + e.StackTrace);
                                    }

                                    if (sampledCalibrationPoints == totalCalibrationPoints)
                                        //Notify calibration listener that all calibration points have been sampled and the analysis of the calirbation results has begun
                                        try
                                        {
                                            calibrationListener.OnCalibrationProcessing();
                                        }
                                        catch (Exception e)
                                        {
                                            Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationProcessing() on listener " + calibrationListener + ": " + e.StackTrace);
                                        }
                                }

                                var cper = JsonConvert.DeserializeObject<CalibrationPointEndReply>(response);

                                if (cper == null || cper.Values.CalibrationResult == null)
                                    break; // not done with calibration yet

                                //if calibration state changed, notify listeners
                                if (cper.Values.CalibrationResult.Result != IsCalibrated)
                                {
                                    lock (((ICollection)calibrationStateListeners).SyncRoot)
                                    {
                                        foreach (ICalibrationResultListener listener in calibrationStateListeners)
                                        {
                                            try
                                            {
                                                listener.OnCalibrationChanged(cper.Values.CalibrationResult.Result, cper.Values.CalibrationResult);
                                            }
                                            catch (Exception e)
                                            {
                                                Debug.WriteLine("Exception while calling ICalibrationStateListener.OnCalibrationChanged() on listener " + listener + ": " + e.StackTrace);
                                            }
                                        }
                                    }
                                }

                                IsCalibrated = cper.Values.CalibrationResult.Result;
                                IsCalibrating = !cper.Values.CalibrationResult.Result;
                                LastCalibrationResult = cper.Values.CalibrationResult;

                                if (null != calibrationListener)
                                {
                                    //Notify calibration listener that calibration results are ready for evaluation
                                    try
                                    {
                                        calibrationListener.OnCalibrationResult(cper.Values.CalibrationResult);
                                    }
                                    catch (Exception e)
                                    {
                                        Debug.WriteLine("Exception while calling ICalibrationProcessHandler.OnCalibrationResult() on listener " + calibrationListener + ": " + e.StackTrace);
                                    }
                                }
                                break;

                            case Protocol.CALIBRATION_REQUEST_ABORT:
                                IsCalibrating = false;

                                //restore states of last calibration if any
                                apiManager.RequestCalibrationStates();
                                break;

                            case Protocol.CALIBRATION_REQUEST_CLEAR:
                                IsCalibrated = false;
                                IsCalibrating = false;
                                LastCalibrationResult = null;
                                break;
                        }
                        break; // end calibration switch

                    case Protocol.CATEGORY_HEARTBEAT:
                        //do nothing
                        break;

                    default:
                        var rf = JsonConvert.DeserializeObject<ReplyFailed>(response);
                        Debug.WriteLine("Request FAILED");
                        Debug.WriteLine("Category: " + rf.Category);
                        Debug.WriteLine("Request: " + rf.Request);
                        Debug.WriteLine("StatusCode: " + rf.StatusCode);
                        Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage);
                        break;
                }
            }
            else
            {
                var rf = JsonConvert.DeserializeObject<ReplyFailed>(response);

                /*
                 * JSON Message status code is different from HttpStatusCode.OK. Check if special TET
                 * specific statuscode before handling error
                 */

                switch (rf.StatusCode)
                {
                    case Protocol.STATUSCODE_CALIBRATION_UPDATE:
                        //The calibration state has changed, clients should update themselves
                        apiManager.RequestCalibrationStates();
                        break;

                    case Protocol.STATUSCODE_SCREEN_UPDATE:
                        //The primary screen index has changed, clients should update themselves
                        apiManager.RequestScreenStates();
                        break;

                    case Protocol.STATUSCODE_TRACKER_UPDATE:
                        //The connected Tracker Device has changed state, clients should update themselves
                        apiManager.RequestTrackerState();
                        break;

                    default:
                        Debug.WriteLine("Request FAILED");
                        Debug.WriteLine("Category: " + rf.Category);
                        Debug.WriteLine("Request: " + rf.Request);
                        Debug.WriteLine("StatusCode: " + rf.StatusCode);
                        Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage);
                        break;
                }

            }
        }
コード例 #28
0
 /// <summary>
 /// Returns a value indicating whether the provided action maps to the specified API version.
 /// </summary>
 /// <param name="action">The <see cref="ActionDescriptor">action</see> to evaluate.</param>
 /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to test the mapping for.</param>
 /// <returns>True if the <paramref name="action"/> explicitly or implicitly maps to the specified
 /// <paramref name="apiVersion">API version</paramref>; otherwise, false.</returns>
 public static bool IsMappedTo(this ActionDescriptor action, ApiVersion apiVersion)
 {
     Arg.NotNull(action, nameof(action));
     return(action.MappingTo(apiVersion) > None);
 }
コード例 #29
0
 /// <summary>
 /// Maps a versioned OData route.
 /// </summary>
 /// <param name="configuration">The extended <see cref="HttpConfiguration">HTTP configuration</see>.</param>
 /// <param name="routeName">The name of the route to map.</param>
 /// <param name="routePrefix">The prefix to add to the OData route's path template.</param>
 /// <param name="model">The <see cref="IEdmModel">EDM model</see> to use for parsing OData paths.</param>
 /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> associated with the model.</param>
 /// <returns>The mapped <see cref="ODataRoute">OData route</see>.</returns>
 /// <remarks>The <see cref="ApiVersionAnnotation">API version annotation</see> will be added or updated on the specified <paramref name="model"/> using
 /// the provided <paramref name="apiVersion">API version</paramref>.</remarks>
 public static ODataRoute MapVersionedODataRoute(this HttpConfiguration configuration, string routeName, string routePrefix, IEdmModel model, ApiVersion apiVersion) =>
 MapVersionedODataRoute(configuration, routeName, routePrefix, model, apiVersion, new DefaultODataPathHandler(), ODataRoutingConventions.CreateDefault(), null, null);
コード例 #30
0
        internal UnversionedODataPathRouteConstraint(IRouteConstraint innerConstraint, ApiVersion apiVersion)
        {
            Contract.Requires(innerConstraint != null);

            innerConstraints = new[] { innerConstraint };
            this.apiVersion  = apiVersion;
        }
コード例 #31
0
        /// <summary>
        /// Determines whether the specified action should be explored for the indicated API version.
        /// </summary>
        /// <param name="actionDescriptor">The <see cref="ActionDescriptor">action</see> to evaluate.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> for action being explored.</param>
        /// <returns>True if the action should be explored; otherwise, false.</returns>
        protected virtual bool ShouldExploreAction(ActionDescriptor actionDescriptor, ApiVersion apiVersion)
        {
            Arg.NotNull(actionDescriptor, nameof(actionDescriptor));
            Arg.NotNull(apiVersion, nameof(actionDescriptor));

            var model = actionDescriptor.GetProperty <ApiVersionModel>();

            if (model != null)
            {
                if (model.IsApiVersionNeutral || model.DeclaredApiVersions.Contains(apiVersion))
                {
                    return(true);
                }

                if (model.DeclaredApiVersions.Count > 0)
                {
                    return(false);
                }
            }

            model = actionDescriptor.GetProperty <ControllerModel>()?.GetProperty <ApiVersionModel>();

            return(model != null && (model.IsApiVersionNeutral || model.DeclaredApiVersions.Contains(apiVersion)));
        }
コード例 #32
0
ファイル: CAdapter.cs プロジェクト: Zulkir/Beholder
        public CAdapter()
        {
            var tempWindow = new GameWindow();
            GraphicsMode bestMode = tempWindow.Context.GraphicsMode;
            var tempContext = new Context(tempWindow.Context);
            var implementation = tempContext.Implementation;
            apiVersion = new ApiVersion((byte)implementation.MajorVersion, (byte)implementation.MinorVersion);
            restrictions = new AdapterRestrictions
            {
                UniformBufferSlots = tempContext.Implementation.MaxUniformBufferBindings,
                SamplerSlots = tempContext.Implementation.MaxCombinedTextureImageUnits, // todo Make those separate
                ShaderResourceSlots = tempContext.Implementation.MaxCombinedTextureImageUnits,
                UnorderedAccessResourceSlots = 0, // todo Set it
                MaxVertexStreams = tempContext.Implementation.MaxVertexAttributes,
                MaxVertexStreamElementCount = 16, // todo: set it
                MaxStreamOutputTargets = tempContext.Implementation.MaxTransformFeedbackSeparateComponents, // todo: make sure
                MaxViewports = tempContext.Implementation.MaxViewports,
                MaxRenderTargets = tempContext.Implementation.MaxColorAttachments,
                MaxThreadGroupsX = 0, // todo: set it,
                MaxThreadGroupsY = 0, // todo: set it,
                MaxThreadGroupsZ = 0,  // todo: set it
                MaxThreadGroupsTotal = 0
            };

            adapterDesc = new AdapterDescription
            {
                Description = GL.GetString(StringName.Renderer),
                VendorId = 0,
                DeviceId = 0,
                SubSysId = 0,
                Revision = 0,
                DedicatedVideoMemory = 0,
                DedicatedSystemMemory = 0,
                SharedSystemMemory = 0,
                AdapterLuidHigh = 0,
                AdapterLuidLow = 0,
                Flags = AdapterFlags.None
            };

            tempWindow.Dispose();

            outputs = GetAvailableDisplays().Select((d, i) => new COutput(d, i)).ToArray();

            //foreach (var format in DisplayColorFormats)
            //{
            //    var expectedColorFormat = CtObjectGL.ColorFormat(format);
            //
            //    tempWindow = new GameWindow(1, 1, new GraphicsMode(expectedColorFormat, bestMode.Depth, bestMode.Stencil));
            //    var actualColorFormat = tempWindow.Context.GraphicsMode.ColorFormat;
            //    tempWindow.Dispose();
            //
            //    if (expectedColorFormat.Red == actualColorFormat.Red &&
            //        expectedColorFormat.Green == actualColorFormat.Green &&
            //        expectedColorFormat.Blue == actualColorFormat.Blue &&
            //        expectedColorFormat.Alpha == actualColorFormat.Alpha)
            //    {
            //        supportedDisplayFormats.Add(format);
            //    }
            //}
        }
コード例 #33
0
ファイル: FeatureLevel.cs プロジェクト: Zulkir/Beholder
 public FeatureLevel(Api api, ApiVersion version)
 {
     Api = api;
     Version = version;
 }
コード例 #34
0
 public static string GetTextForApiVersion(ApiVersion apiVersion)
 {
     return Lang.ResourceManager.GetString("ApiVersion_" + apiVersion.ToString(), Lang.Culture);
 }
コード例 #35
0
ファイル: BaseAPI.cs プロジェクト: caideyuan/ObsidianToolkit
        protected ActionRequest PrepareViewRequest(string viewCode, Entity oQuery, ApiVersion ver)
        {
            if (ver == ApiVersion.V2)
            {
                ActionRequest req = new ActionRequest("ext.view.display");

                Dictionary<string, object> dictViewQry = new Dictionary<string, object>();
                dictViewQry.Add("viewCode", viewCode);
                req.AddParam("viewQry", dictViewQry);

                Dictionary<string, object> dictQryCourse = new Dictionary<string, object>();
                req.AddParam("qry", oQuery.ToDictionary());

                return req;
            }
            else if (ver == ApiVersion.V3)
            {
                ActionRequest req = new ActionRequest("odv.view.display");

                Dictionary<string, object> dictViewQry = new Dictionary<string, object>();
                dictViewQry.Add("viewCode", viewCode);
                req.AddParam("view", dictViewQry);

                Dictionary<string, object> dictQryCourse = new Dictionary<string, object>();
                req.AddParam("qry", oQuery.ToDictionary());

                return req;
            }
            throw new Exception("未知API版本");
        }
コード例 #36
0
ファイル: GazeManager.cs プロジェクト: e-/tet-csharp-client
 /// <summary>
 /// Activates TET C# Client and all underlying routines using default values. Should be called _only_ 
 /// once when an application starts up. Calling thread will be locked during
 /// initialization.
 /// </summary>
 /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param>
 /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param>
 /// <param name="listener">Listener to notify once the connection to EyeTribe Server has been established</param>
 /// <returns>True if succesfully activated, false otherwise</returns>
 public bool Activate(ApiVersion apiVersion, ClientMode mode, IConnectionStateListener listener)
 {
     AddConnectionStateListener(listener);
     return Activate(apiVersion, mode, GazeApiManager.DEFAULT_SERVER_HOST, GazeApiManager.DEFAULT_SERVER_PORT);
 }
コード例 #37
0
 /// <summary>
 /// Compares the current <see cref="ApiVersion"/> with another object of the same type. The default version does not allow sorting and returns zero.
 /// </summary>
 /// <returns>
 /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. 
 /// </returns>
 /// <param name="other"></param>
 /// <returns></returns>
 protected override int CompareToVersion(ApiVersion other) {
     return this.Version.CompareTo(((SemVerApiVersion) other).Version);
 }
コード例 #38
0
ファイル: GazeManager.cs プロジェクト: e-/tet-csharp-client
        /// <summary>
        /// Activates TET C# Client and all underlying routines. Should be called _only_ 
        /// once when an application starts up. Calling thread will be locked during
        /// initialization.
        /// </summary>
        /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param>
        /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param>
        /// <param name="hostname">The host name or IP address where the eye tracking server is running.</param>
        /// <param name="portnumber">The port number used for the eye tracking server</param>
        /// <returns>True if succesfully activated, false otherwise</returns>
        public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber)
        {
            //lock to ensure that state changing method calls are synchronous
            lock (Instance)
            {
                Object threadLock = Thread.CurrentThread;

                //lock calling thread while initializing
                lock (threadLock)
                {
                    //only one entity can initialize at the time
                    lock (initializationLock)
                    {
                        if (!IsActivated)
                        {
                            isInizializing = true;

                            try
                            {
                                //establish connection in seperate thread
                                apiManager = new GazeApiManager(this, this);
                                ThreadPool.QueueUserWorkItem(new WaitCallback(HandleServerConnect), new Object[] { apiManager, mode, apiVersion, hostname, portnumber });

                                //We wait untill above requests have been handled by server or timeout occurs
                                bool waitSuccess = Monitor.Wait(initializationLock, TimeSpan.FromSeconds(INIT_TIME_DELAY_SECONDS));

                                if (!waitSuccess)
                                {
                                    HandleInitFailure();

                                    Console.Write("Error initializing GazeManager, is EyeTribe Server running?");
                                }
                                else
                                {
                                    //init heartbeat
                                    heartbeatHandler = new Heartbeat(apiManager);
                                    heartbeatHandler.Start();

                                    isActive = true;

                                    //notify connection listeners
                                    OnGazeApiConnectionStateChanged(IsActivated);
                                }
                            }
                            catch (Exception e)
                            {
                                HandleInitFailure();

                                Console.Write("Error initializing GazeManager: " + e.StackTrace);
                            }
                        }

                        return IsActivated;
                    }
                }
            }
        }
コード例 #39
0
 public string Get(ApiVersion apiVersion)
 => $"Controller = {GetType().Name}\nVersion = {apiVersion}";
コード例 #40
0
        public async Task <ActionResult <WorkflowDefinition> > Handle([FromBody] SaveWorkflowDefinitionRequest request, [FromRoute] ApiVersion apiVersion, CancellationToken cancellationToken)
        {
            var workflowDefinitionId = request.WorkflowDefinitionId;
            var workflowDefinition   = !string.IsNullOrWhiteSpace(workflowDefinitionId) ? await _workflowPublisher.GetDraftAsync(workflowDefinitionId, cancellationToken) : default;

            var isNew = workflowDefinition == null;

            if (workflowDefinition == null)
            {
                workflowDefinition = _workflowPublisher.New();

                if (!string.IsNullOrWhiteSpace(workflowDefinitionId))
                {
                    workflowDefinition.DefinitionId = workflowDefinitionId;
                }
            }

            workflowDefinition.Activities               = request.Activities;
            workflowDefinition.Connections              = FilterInvalidConnections(request).ToList();
            workflowDefinition.Description              = request.Description?.Trim();
            workflowDefinition.Name                     = request.Name?.Trim();
            workflowDefinition.Variables                = request.Variables ?? new Variables();
            workflowDefinition.IsSingleton              = request.IsSingleton;
            workflowDefinition.PersistenceBehavior      = request.PersistenceBehavior;
            workflowDefinition.DeleteCompletedInstances = request.DeleteCompletedInstances;
            workflowDefinition.ContextOptions           = request.ContextOptions;
            workflowDefinition.DisplayName              = request.DisplayName?.Trim();
            workflowDefinition.Tag     = request.Tag?.Trim();
            workflowDefinition.Channel = request.Channel?.Trim();

            workflowDefinition.TenantId = await _tenantAccessor.GetTenantIdAsync(cancellationToken);

            if (request.Publish)
            {
                workflowDefinition = await _workflowPublisher.PublishAsync(workflowDefinition, cancellationToken);
            }
            else
            {
                workflowDefinition = await _workflowPublisher.SaveDraftAsync(workflowDefinition, cancellationToken);
            }

            return(isNew
                ? CreatedAtAction("Handle", "GetByVersionId", new { versionId = workflowDefinition.Id, apiVersion = apiVersion.ToString() }, workflowDefinition)
                : Ok(workflowDefinition));
        }
コード例 #41
0
ファイル: CAdapter.cs プロジェクト: Zulkir/Beholder
        public CAdapter(Adapter1 dxgiAdapter, int index)
        {
            this.dxgiAdapter = dxgiAdapter;
            this.index = index;

            AdapterDescription1 dxgiDesc = dxgiAdapter.Description1;
            desc = new AdapterDescription
            {
                Description = dxgiDesc.Description,
                VendorId = dxgiDesc.VendorId,
                DeviceId = dxgiDesc.DeviceId,
                SubSysId = dxgiDesc.SubsystemId,
                Revision = dxgiDesc.Revision,
                DedicatedVideoMemory = dxgiDesc.DedicatedVideoMemory,
                DedicatedSystemMemory = dxgiDesc.DedicatedSystemMemory,
                SharedSystemMemory = dxgiDesc.SharedSystemMemory,
                AdapterLuidHigh = (int)(dxgiDesc.Luid >> 32),
                AdapterLuidLow = (int)(dxgiDesc.Luid & 0x00000000FFFFFFFF),
                Flags = CtBeholder.AdapterFlags(dxgiDesc.Flags)
            };

            outputs = dxgiAdapter.Outputs.Select(o => new COutput(o)).ToArray();

            using (var d3dDevice = new Device(dxgiAdapter))
            {
                switch (d3dDevice.FeatureLevel)
                {
                    case FeatureLevel.Level_9_1: apiVersion = new ApiVersion(9, 1); break;
                    case FeatureLevel.Level_9_3: apiVersion = new ApiVersion(9, 3); break;
                    case FeatureLevel.Level_9_2: apiVersion = new ApiVersion(9, 2); break;
                    case FeatureLevel.Level_10_0: apiVersion = new ApiVersion(10, 0); break;
                    case FeatureLevel.Level_10_1: apiVersion = new ApiVersion(10, 1); break;
                    case FeatureLevel.Level_11_0: apiVersion = new ApiVersion(11, 0); break;
                    default: throw new ArgumentOutOfRangeException("d3dDevice.FeatureLevel");
                }

                restrictions = new AdapterRestrictions
                {
                    UniformBufferSlots = CommonShaderStage.ConstantBufferApiSlotCount,
                    SamplerSlots = CommonShaderStage.SamplerSlotCount,
                    ShaderResourceSlots = CommonShaderStage.InputResourceSlotCount,
                    UnorderedAccessResourceSlots = ComputeShaderStage.UnorderedAccessViewSlotCount,
                    MaxVertexStreams = InputAssemblerStage.VertexInputResourceSlotCount,
                    MaxVertexStreamElementCount = InputAssemblerStage.VertexInputStructureElementCount,
                    MaxStreamOutputTargets = 4,
                    MaxViewports = 16,
                    MaxRenderTargets = 8,
                    MaxThreadGroupsX = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumX : 768,
                    MaxThreadGroupsY = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumY : 768,
                    MaxThreadGroupsZ = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumZ : 1,
                    MaxThreadGroupsTotal = d3dDevice.FeatureLevel == FeatureLevel.Level_11_0 ? ComputeShaderStage.ThreadGroupMaximumThreadsPerGroup : 768
                };

                var allFormats = ((ExplicitFormat[])Enum.GetValues(typeof(ExplicitFormat))).Select(x => (Format)x).ToArray();

                formatsSupport = allFormats.Select(d3dDevice.CheckFormatSupport).ToArray();
                formatInfos = allFormats.Where(f => f != 0).Select(CtBeholder.FormatInfo).ToArray();
                //depthStencilFormatInfos = allFormats.Where(f => (formatsSupport[(int)f] & DepthStencilSupportMask) != 0).Select(CtBeholder.DepthStencilFormatInfo).ToArray();
                vertexElementFormats = allFormats.Where(f => (formatsSupport[(int)f] & VertexElementSupportMask) != 0).Select(f => (ExplicitFormat)f).ToArray();

                multisampleQualityLevels = new int[allFormats.Length, MultisampleCountsToTry.Length];

                for (int i = 0; i < allFormats.Length; i++)
                    for (int j = 0; j < MultisampleCountsToTry.Length; j++)
                        multisampleQualityLevels[i, j] = d3dDevice.CheckMultisampleQualityLevels((Format)i, MultisampleCountsToTry[j]);
            }
            /*
            using (var writer = new System.IO.StreamWriter("Formats.txt"))
            {
                for (int i = 0; i < formatsSupport.Length; i++)
                {
                    writer.WriteLine(string.Format("{0, -30}:{1}", (Format)i, formatsSupport[i].ToString().Replace(", ", " | ")));
                }
            }*/
        }
コード例 #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CardService"/> class.
 /// </summary>
 /// <param name="serviceAdapter">The service adapter used to interact with the MTG API.</param>
 /// <param name="version">The version of the API</param>
 /// <param name="rateLimitOn">Turn the rate limit on or off.</param>
 public CardService(IMtgApiServiceAdapter serviceAdapter, ApiVersion version, bool rateLimitOn = true)
     : base(serviceAdapter, version, ApiEndPoint.Cards, rateLimitOn)
 {
     _whereQueries = new NameValueCollection();
 }
コード例 #43
0
ファイル: GazeManager.cs プロジェクト: e-/tet-csharp-client
        internal void HandleApiResponse(Object stateInfo)
        {
            try
            {
                String response = (String)stateInfo;

                var reply = JsonConvert.DeserializeObject<ReplyBase>(response);

                if (reply.StatusCode == (int)HttpStatusCode.OK)
                {
                    switch (reply.Category)
                    {
                        case Protocol.CATEGORY_TRACKER:

                            if (reply.Request.Equals(Protocol.TRACKER_REQUEST_GET))
                            {
                                var jsreader = new JsonTextReader(new StringReader(response));
                                var json = (JObject)new JsonSerializer().Deserialize(jsreader);

                                JObject values = null != json[Protocol.KEY_VALUES] ? json[Protocol.KEY_VALUES].ToObject<JObject>() : null;
                                JToken value;

                                if (null != values)
                                {
                                    if (values.TryGetValue(Protocol.TRACKER_VERSION, out value))
                                        version = value.ToObject<ApiVersion>();

                                    if (values.TryGetValue(Protocol.TRACKER_MODE_PUSH, out value))
                                    {
                                        if ((bool)value)
                                            clientMode = ClientMode.Push;
                                        else
                                            clientMode = ClientMode.Pull;
                                    }

                                    if (values.TryGetValue(Protocol.TRACKER_HEARTBEATINTERVAL, out value))
                                        HeartbeatMillis = (int)value;

                                    if (values.TryGetValue(Protocol.TRACKER_FRAMERATE, out value))
                                        Framerate = value.ToObject<FrameRate>();

                                    if (values.TryGetValue(Protocol.TRACKER_TRACKERSTATE, out value))
                                    {
                                        //if tracker state changed, notify listeners
                                        if ((int)value != (int)Convert.ChangeType(Trackerstate, Trackerstate.GetTypeCode()))
                                        {
                                            Trackerstate = (TrackerState)(int)value;

                                            foreach (ITrackerStateListener listener in trackerStateListeners)
                                            {
                                                ThreadPool.QueueUserWorkItem(new WaitCallback(HandleOnTrackerStateChanged), new Object[] { listener, Trackerstate });
                                            }
                                        }
                                    }

                                    if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATING, out value))
                                        IsCalibrating = (bool)value;

                                    if (values.TryGetValue(Protocol.TRACKER_ISCALIBRATED, out value))
                                        IsCalibrated = (bool)value;

                                    if (values.TryGetValue(Protocol.TRACKER_CALIBRATIONRESULT, out value))
                                    {
                                        //is result different from current?
                                        if (null == LastCalibrationResult || !LastCalibrationResult.Equals(value.ToObject<CalibrationResult>()))
                                        {
                                            LastCalibrationResult = value.ToObject<CalibrationResult>();

                                            foreach (ICalibrationResultListener listener in calibrationResultListeners)
                                            {
                                                ThreadPool.QueueUserWorkItem(new WaitCallback(HandleOnCalibrationChanged), new Object[] { listener, IsCalibrated, LastCalibrationResult });
                                            }
                                        }
                                    }

                                    if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_WIDTH, out value))
                                        ScreenResolutionWidth = (int)value;

                                    if (values.TryGetValue(Protocol.TRACKER_SCREEN_RESOLUTION_HEIGHT, out value))
                                        ScreenResolutionHeight = (int)value;

                                    if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_WIDTH, out value))
                                        ScreenPhysicalWidth = (float)value;

                                    if (values.TryGetValue(Protocol.TRACKER_SCREEN_PHYSICAL_HEIGHT, out value))
                                        ScreenPhysicalHeight = (float)value;

                                    if (values.TryGetValue(Protocol.TRACKER_SCREEN_INDEX, out value))
                                    {
                                        //if screen index changed, notify listeners
                                        if ((int)value != ScreenIndex)
                                        {
                                            ScreenIndex = (int)value;

                                            foreach (ITrackerStateListener listener in trackerStateListeners)
                                            {
                                                ThreadPool.QueueUserWorkItem(new WaitCallback(HandleOnScreenStatesChanged), new Object[] { listener, ScreenIndex, ScreenResolutionWidth, ScreenResolutionHeight, ScreenPhysicalWidth, ScreenPhysicalHeight });
                                            }
                                        }
                                    }

                                    if (values.TryGetValue(Protocol.TRACKER_FRAME, out value) && null != gazeBroadcaster)
                                    {
                                        GazeData gd = value.ToObject<GazeData>();

                                        //fixing timestamp based on string representation, Json 32bit int issue
                                        if (!String.IsNullOrEmpty(gd.TimeStampString))
                                        {
                                            try
                                            {
                                                DateTime gdTime = DateTime.ParseExact(gd.TimeStampString, GazeData.TIMESTAMP_STRING_FORMAT,
                                                    System.Globalization.CultureInfo.InvariantCulture);
                                                gd.TimeStamp = (long)((double)gdTime.Ticks / TimeSpan.TicksPerMillisecond);
                                            }
                                            catch (Exception e)
                                            {
                                                //consume possible error
                                            }
                                        }

                                        //Add gaze update to high frequency broadcasting queue
                                        gazeQueue.Put(gd);
                                    }
                                }

                                //Handle initialization
                                if (isInizializing)
                                {
                                    //we make sure response is inital get request and not a 'push mode' frame
                                    if (!values.TryGetValue(Protocol.TRACKER_FRAME, out value))
                                    {
                                        lock (initializationLock)
                                        {
                                            isInizializing = false;
                                            Monitor.Pulse(initializationLock);
                                        }
                                    }
                                }
                            }
                            else if (reply.Request.Equals(Protocol.TRACKER_REQUEST_SET))
                            {
                                //Do nothing
                            }
                            break;

                        case Protocol.CATEGORY_CALIBRATION:

                            switch (reply.Request)
                            {
                                case Protocol.CALIBRATION_REQUEST_START:

                                    IsCalibrating = true;

                                    if (null != calibrationListener)
                                        //Notify calibration listener that a new calibration process was successfully started
                                        try
                                        {
                                            calibrationListener.OnCalibrationStarted();
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Write("Exception while calling ICalibrationProcessHandler.OnCalibrationStarted() on listener " + calibrationListener + ": " + e.StackTrace);
                                        }

                                    break;

                                case Protocol.CALIBRATION_REQUEST_POINTSTART:
                                    break;

                                case Protocol.CALIBRATION_REQUEST_POINTEND:

                                    ++sampledCalibrationPoints;

                                    if (null != calibrationListener)
                                    {
                                        //Notify calibration listener that a new calibration point has been sampled
                                        try
                                        {
                                            calibrationListener.OnCalibrationProgress((double)sampledCalibrationPoints / totalCalibrationPoints);
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Write("Exception while calling ICalibrationProcessHandler.OnCalibrationProgress() on listener " + calibrationListener + ": " + e.StackTrace);
                                        }

                                        if (sampledCalibrationPoints == totalCalibrationPoints)
                                            //Notify calibration listener that all calibration points have been sampled and the analysis of the calirbation results has begun
                                            try
                                            {
                                                calibrationListener.OnCalibrationProcessing();
                                            }
                                            catch (Exception e)
                                            {
                                                Console.Write("Exception while calling ICalibrationProcessHandler.OnCalibrationProcessing() on listener " + calibrationListener + ": " + e.StackTrace);
                                            }
                                    }

                                    var cper = JsonConvert.DeserializeObject<CalibrationPointEndReply>(response);

                                    if (cper == null || cper.Values.CalibrationResult == null)
                                        break; // not done with calibration yet

                                    IsCalibrated = cper.Values.CalibrationResult.Result;
                                    IsCalibrating = !cper.Values.CalibrationResult.Result;

                                    // Evaluate resample points
                                    sampledCalibrationPoints -= cper.Values.CalibrationResult.Calibpoints.Where(cp => cp.State == CalibrationPoint.STATE_RESAMPLE || cp.State == CalibrationPoint.STATE_NO_DATA).Count();

                                    // Notify calibration result listeners if calibration changed
                                    if (IsCalibrated && (null == LastCalibrationResult || !LastCalibrationResult.Equals(cper.Values.CalibrationResult)))
                                    {
                                        LastCalibrationResult = cper.Values.CalibrationResult;

                                        foreach (ICalibrationResultListener listener in calibrationResultListeners)
                                        {
                                            ThreadPool.QueueUserWorkItem(new WaitCallback(HandleOnCalibrationChanged), new Object[] { listener, IsCalibrated, LastCalibrationResult });
                                        }
                                    }

                                    if (null != calibrationListener)
                                    {
                                        // Notify calibration listener that calibration results are ready for evaluation
                                        try
                                        {
                                            calibrationListener.OnCalibrationResult(cper.Values.CalibrationResult);
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Write("Exception while calling ICalibrationProcessHandler.OnCalibrationResult() on listener " + calibrationListener + ": " + e.StackTrace);
                                        }
                                    }
                                    break;

                                case Protocol.CALIBRATION_REQUEST_ABORT:
                                    IsCalibrating = false;

                                    //restore states of last calibration if any
                                    apiManager.RequestCalibrationStates();
                                    break;

                                case Protocol.CALIBRATION_REQUEST_CLEAR:
                                    IsCalibrated = false;
                                    IsCalibrating = false;
                                    LastCalibrationResult = null;
                                    break;
                            }
                            break; // end calibration switch

                        case Protocol.CATEGORY_HEARTBEAT:
                            //do nothing
                            break;

                        default:
                            var rf = JsonConvert.DeserializeObject<ReplyFailed>(response);
                            Debug.WriteLine("Request FAILED");
                            Debug.WriteLine("Category: " + rf.Category);
                            Debug.WriteLine("Request: " + rf.Request);
                            Debug.WriteLine("StatusCode: " + rf.StatusCode);
                            Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage);
                            break;
                    }
                }
                else
                {
                    var rf = JsonConvert.DeserializeObject<ReplyFailed>(response);

                    /*
                     * JSON Message status code is different from HttpStatusCode.OK. Check if special TET
                     * specific statuscode before handling error
                     */

                    switch (rf.StatusCode)
                    {
                        case Protocol.STATUSCODE_CALIBRATION_UPDATE:
                            //The calibration state has changed, clients should update themselves
                            apiManager.RequestCalibrationStates();
                            break;

                        case Protocol.STATUSCODE_SCREEN_UPDATE:
                            //The primary screen index has changed, clients should update themselves
                            apiManager.RequestScreenStates();
                            break;

                        case Protocol.STATUSCODE_TRACKER_UPDATE:
                            //The connected Tracker Device has changed state, clients should update themselves
                            apiManager.RequestTrackerState();
                            break;

                        default:
                            Debug.WriteLine("Request FAILED");
                            Debug.WriteLine("Category: " + rf.Category);
                            Debug.WriteLine("Request: " + rf.Request);
                            Debug.WriteLine("StatusCode: " + rf.StatusCode);
                            Debug.WriteLine("StatusMessage: " + rf.Values.StatusMessage);
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception while parsing API response: " + e.StackTrace);
            }
        }
コード例 #44
0
        public KeyValuePair <int, string> GeneralRequest(string url, string method, string payload = null, ApiVersion api = ApiVersion.V5, string clientId = null, string accessToken = null)
        {
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method     = new HttpMethod(method)
            };

            if (string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidCredentialException("A Client-Id or OAuth token is required to use the Twitch API. If you previously set them in InitializeAsync, please be sure to await the method.");
            }

            if (!string.IsNullOrEmpty(clientId))
            {
                request.Headers.Add("Client-ID", clientId);
            }

            var authPrefix = "OAuth";

            if (api == ApiVersion.Helix)
            {
                request.Headers.Add(HttpRequestHeader.Accept.ToString(), "application/json");
                authPrefix = "Bearer";
            }
            else if (api != ApiVersion.Void)
            {
                request.Headers.Add(HttpRequestHeader.Accept.ToString(), $"application/vnd.twitchtv.v{(int)api}+json");
            }
            if (!string.IsNullOrEmpty(accessToken))
            {
                request.Headers.Add(HttpRequestHeader.Authorization.ToString(), $"{authPrefix} {Common.Helpers.FormatOAuth(accessToken)}");
            }

            if (payload != null)
            {
                request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
            }


            var response = _http.SendAsync(request).GetAwaiter().GetResult();

            if (response.IsSuccessStatusCode)
            {
                var respStr = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                return(new KeyValuePair <int, string>((int)response.StatusCode, respStr));
            }

            HandleWebException(response);
            return(new KeyValuePair <int, string>(0, null));
        }
コード例 #45
0
ファイル: GazeManager.cs プロジェクト: e-/tet-csharp-client
 /// <summary>
 /// Activates TET C# Client and all underlying routines. Should be called _only_ 
 /// once when an application starts up. Calling thread will be locked during
 /// initialization.
 /// </summary>
 /// <param name="apiVersion">Version number of the Tracker API that this client will be compliant to</param>
 /// <param name="mode">Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param>
 /// <param name="hostname">The host name or IP address where the eye tracking server is running.</param>
 /// <param name="portnumber">The port number used for the eye tracking server</param>
 /// <param name="listener">Listener to notify once the connection to EyeTribe Server has been established</param> 
 /// <returns>True if succesfully activated, false otherwise</returns>
 public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber, IConnectionStateListener listener)
 {
     AddConnectionStateListener(listener);
     return Activate(apiVersion, mode, hostname, portnumber, listener);
 }
コード例 #46
0
        /// <summary>
        /// Determines whether the controller should be considered.
        /// </summary>
        /// <param name="controllerRouteParameterValue">The controller route parameter value.</param>
        /// <param name="controllerDescriptor">The associated <see cref="HttpControllerDescriptor">controller descriptor</see>.</param>
        /// <param name="route">The associated <see cref="IHttpRoute">route</see>.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to consider the controller for.</param>
        /// <returns>True if the controller should be explored; otherwise, false.</returns>
        protected override bool ShouldExploreController(string controllerRouteParameterValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route, ApiVersion apiVersion)
        {
            Arg.NotNull(controllerDescriptor, nameof(controllerDescriptor));
            Arg.NotNull(route, nameof(route));
            Arg.NotNull(apiVersion, nameof(apiVersion));

            if (typeof(MetadataController).IsAssignableFrom(controllerDescriptor.ControllerType))
            {
                return(false);
            }

            var routeTemplate = route.RouteTemplate;

            if (!odataVariableRegex.IsMatch(routeTemplate))
            {
                return(base.ShouldExploreController(controllerRouteParameterValue, controllerDescriptor, route, apiVersion));
            }

            if (Options.UseApiExplorerSettings)
            {
                var setting = controllerDescriptor.GetCustomAttributes <ApiExplorerSettingsAttribute>().FirstOrDefault();

                if (setting?.IgnoreApi == true)
                {
                    return(false);
                }
            }

            var model = controllerDescriptor.GetApiVersionModel();

            return(model.IsApiVersionNeutral || model.DeclaredApiVersions.Contains(apiVersion));
        }
コード例 #47
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="gatewayUri"></param>
 /// <param name="version"></param>
 public FdGatewayManager(string gatewayUri, ApiVersion version)
 {
     GatewayUri = gatewayUri;
     Version = version;
 }
コード例 #48
0
        /// <summary>
        /// Explores controllers that do not use direct routes (aka "attribute" routing)
        /// </summary>
        /// <param name="controllerMappings">The <see cref="IDictionary{TKey, TValue}">collection</see> of controller mappings.</param>
        /// <param name="route">The <see cref="IHttpRoute">route</see> to explore.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to explore.</param>
        /// <returns>The <see cref="Collection{T}">collection</see> of discovered <see cref="VersionedApiDescription">API descriptions</see>.</returns>
        protected override Collection <VersionedApiDescription> ExploreRouteControllers(IDictionary <string, HttpControllerDescriptor> controllerMappings, IHttpRoute route, ApiVersion apiVersion)
        {
            if (!(route is ODataRoute))
            {
                return(base.ExploreRouteControllers(controllerMappings, route, apiVersion));
            }

            var apiDescriptions = new Collection <VersionedApiDescription>();
            var edmModel        = Configuration.GetODataRootContainer(route).GetRequiredService <IEdmModel>();
            var routeApiVersion = edmModel.GetAnnotationValue <ApiVersionAnnotation>(edmModel)?.ApiVersion;

            if (routeApiVersion != apiVersion)
            {
                return(apiDescriptions);
            }

            var actionSelector = Configuration.Services.GetActionSelector();

            foreach (var controllerMapping in controllerMappings)
            {
                var controllerVariableValue = controllerMapping.Key;

                foreach (var controllerDescriptor in controllerMapping.Value.AsEnumerable())
                {
                    if (ShouldExploreController(controllerVariableValue, controllerDescriptor, route, apiVersion))
                    {
                        ExploreRouteActions(route, controllerDescriptor, actionSelector, apiDescriptions, apiVersion);
                    }
                }
            }

            return(apiDescriptions);
        }
コード例 #49
0
ファイル: GroupmeApi.cs プロジェクト: legendz3/GroupMeBot
        private RestResponse SendJsonRequest(string resource, Method method, object body = null, Dictionary<string, object> parameters = null, ApiVersion? version = null)
        {
            var request = new RestRequest(resource, method) { RequestFormat = DataFormat.Json };
            request.AddHeader("X-Access-Token", _token);

            if (body != null)
                request.AddBody(body);
            if (parameters != null && parameters.Count > 0)
            {
                foreach (KeyValuePair<string, object> parameter in parameters)
                {
                    request.AddParameter(parameter.Key, parameter.Value);
                }
            }

            RestClient client = version.HasValue ? GeClientByVersion(version.Value) : _defaultClient;
            var response = (RestResponse)client.Execute(request);

            return response;
        }
コード例 #50
0
        /// <summary>
        /// Determines whether the action should be considered.
        /// </summary>
        /// <param name="actionRouteParameterValue">The action route parameter value.</param>
        /// <param name="actionDescriptor">The associated <see cref="HttpActionDescriptor">action descriptor</see>.</param>
        /// <param name="route">The associated <see cref="IHttpRoute">route</see>.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> to consider the controller for.</param>
        /// <returns>True if the action should be explored; otherwise, false.</returns>
        protected override bool ShouldExploreAction(string actionRouteParameterValue, HttpActionDescriptor actionDescriptor, IHttpRoute route, ApiVersion apiVersion)
        {
            Arg.NotNull(actionDescriptor, nameof(actionDescriptor));
            Arg.NotNull(route, nameof(route));
            Arg.NotNull(apiVersion, nameof(apiVersion));

            if (!(route is ODataRoute))
            {
                return(base.ShouldExploreAction(actionRouteParameterValue, actionDescriptor, route, apiVersion));
            }

            if (Options.UseApiExplorerSettings)
            {
                var setting = actionDescriptor.GetCustomAttributes <ApiExplorerSettingsAttribute>().FirstOrDefault();

                if (setting?.IgnoreApi == true)
                {
                    return(false);
                }
            }

            var model = actionDescriptor.GetApiVersionModel();

            if (model.IsApiVersionNeutral || model.DeclaredApiVersions.Contains(apiVersion))
            {
                return(true);
            }

            if (model.DeclaredApiVersions.Count == 0)
            {
                model = actionDescriptor.ControllerDescriptor.GetApiVersionModel();
                return(model.IsApiVersionNeutral || model.DeclaredApiVersions.Contains(apiVersion));
            }

            return(false);
        }
コード例 #51
0
 /// <summary>
 /// Indicates whether the current object is equal to another object of the same type.
 /// </summary>
 /// <returns>
 /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
 /// </returns>
 /// <param name="other">An object to compare with this object.</param>
 public override bool Equals(ApiVersion other) {
     return ReferenceEquals(other, this);
 }
コード例 #52
0
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string?routePrefix)
 {
     builder.EntitySet <GreetingEntity>("Greetings").EntityType
     .HasKey(_ => _.Message)
     .Select().Count();
 }
コード例 #53
0
        /// <summary>
        /// Activates TET C# Client and all underlying routines. Should be called _only_ 
        /// once when an application starts up. Calling thread will be locked during
        /// initialization.
        /// </summary>
        /// <param name="apiVersion"/>Version number of the Tracker API that this client will be compliant to</param>
        /// <param name="mode"/>Mode though which the client will receive GazeData. Either ClientMode.Push or ClientMode.Pull</param>
        /// <param name="hostname"/>The host name or IP address where the eye tracking server is running.</param>
        /// <param name="portnumber"/>The port number used for the eye tracking server</param>
        /// <returns>True is succesfully activated, false otherwise</returns>
        public bool Activate(ApiVersion apiVersion, ClientMode mode, string hostname, int portnumber)
        {
            //if already running, deactivate before starting anew
            if (isActive)
                Deactivate();

            //lock calling thread while initializing
            initializationLock = Thread.CurrentThread;
            lock (initializationLock)
            {
                apiManager = new GazeApiManager(this);
                apiManager.Connect(hostname, portnumber);

                if (apiManager.IsConnected())
                {
                    apiManager.RequestTracker(mode, apiVersion);
                    apiManager.RequestAllStates();

                    //We wait untill above requests have been handled by server or timeout occours
                    bool waitSuccess = Monitor.Wait(initializationLock, TimeSpan.FromSeconds(20));

                    if (waitSuccess == false)
                    {
                        Debug.WriteLine("Error initializing GazeManager");
                        return false;
                    }

                    //init heartbeat
                    heartbeatHandler = new Heartbeat(apiManager);
                    heartbeatHandler.Start();

                    isActive = true;
                }
                else
                    Debug.WriteLine("Error initializing GazeManager");

                return isActive;
            }
        }
コード例 #54
0
ファイル: Startup.cs プロジェクト: Azure/ace-luna
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(
                options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => this.configuration.Bind("AzureAd", options));

            services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
            .AddAzureADBearer(options => this.configuration.Bind("AzureAd", options));

            AADAuthHelper.AdminList = this.configuration["ISVPortal:AdminAccounts"].Split(';', StringSplitOptions.RemoveEmptyEntries);

            AADAuthHelper.AdminTenantId = this.configuration["ISVPortal:AdminTenant"];

            services.Configure <JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
            {
                // This is a Microsoft identity platform web API.
                options.Authority += "/v2.0";

                // The web API accepts as audiences both the Client ID (options.Audience) and api://{ClientID}.
                options.TokenValidationParameters.ValidAudiences = new[]
                {
                    options.Audience,
                    $"api://{options.Audience}",
                    this.configuration["AzureAD:ClientId"],
                    $"api://{this.configuration["AzureAD:ClientId"]}"
                };
                options.ClaimsIssuer = @"https://sts.windows.net/{tenantid}/";

                // Instead of using the default validation (validating against a single tenant,
                // as we do in line-of-business apps),
                // we inject our own multitenant validation logic (which even accepts both v1 and v2 tokens).
                options.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetIssuerValidator(options.Authority).Validate;
            });

            services.Configure <CookieAuthenticationOptions>(
                AzureADDefaults.CookieScheme,
                options => options.AccessDeniedPath = "/Subscriptions/NotAuthorized");

            services.Configure <OpenIdConnectOptions>(
                AzureADDefaults.OpenIdScheme,
                options =>
            {
                //options.Authority = options.Authority + "/v2.0/"; // Azure AD v2.0

                options.TokenValidationParameters.ValidateIssuer =
                    false;         // accept several tenants (here simplified)
            });


            services.Configure <DashboardOptions>(this.configuration.GetSection("Dashboard"));

            services.Configure <AzureOptions>(this.configuration.GetSection("Azure"));

            services.Configure <ApiBehaviorOptions>(x =>
            {
                x.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetails = new ErrorModel(context);
                    return(new BadRequestObjectResult(problemDetails)
                    {
                        ContentTypes = { "application/problem+json", "application/problem+xml" }
                    });
                };
            });

            services.AddOptions <SecuredFulfillmentClientConfiguration>().Configure(
                options => {
                this.configuration.Bind("FulfillmentClient", options);
                this.configuration.Bind("SecuredCredentials:Marketplace", options);
            }
                );
            services.AddHttpClient <IFulfillmentClient, FulfillmentClient>()
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))      //Set lifetime to five minutes
            .AddPolicyHandler(
                (services, request) => HttpPolicyExtensions.HandleTransientHttpError()
                .OrResult(msg => ExceptionUtils.IsHttpErrorCodeRetryable(msg.StatusCode))
                .WaitAndRetryAsync(
                    3,
                    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                    onRetry: (result, timeSpan, retryCount, context) =>
            {
                if (result.Exception != null)
                {
                    services.GetService <ILogger <IFulfillmentClient> >()?
                    .LogWarning($"An exception occurred on retry {retryCount} at {context.OperationKey} with message {result.Exception.Message}");
                }
                else
                {
                    services.GetService <ILogger <IFulfillmentClient> >()?
                    .LogError($"An unsuccessful status code {result.Result.StatusCode} was received on retry {retryCount} at {context.OperationKey}");
                }
            }
                    ));

            // Hack to save the host name and port during the handling the request. Please see the WebhookController and ContosoWebhookHandler implementations
            services.AddSingleton <ContosoWebhookHandlerOptions>();


            services.TryAddScoped <IWebhookProcessor, WebhookProcessor>();

            services.TryAddScoped <IFulfillmentManager, FulfillmentManager>();

            // Register the provisioning client
            services.AddOptions <SecuredProvisioningClientConfiguration>().Configure(
                options => {
                this.configuration.Bind("ProvisioningClient", options);
                this.configuration.Bind("SecuredCredentials:ResourceManager", options);
            }
                );
            //services.TryAddScoped<IProvisioningClient, ProvisioningClient>();
            services.AddHttpClient <IProvisioningClient, ProvisioningClient>()
            .SetHandlerLifetime(TimeSpan.FromMinutes(5));


            services.AddHttpClient <ICustomMeteringClient, CustomMeteringClient>();

            // Get the connection string from appsettings.json
            string connectionString = this.configuration.GetValue <string>(this.configuration["SecuredCredentials:Database:ConnectionString"]);

            // Database context must be registered with the dependency injection (DI) container
            services.AddDbContext <SqlDbContext>(options =>
                                                 options.UseSqlServer(connectionString));

            // Register the db context interface
            services.TryAddScoped <ISqlDbContext, SqlDbContext>();


            services.AddOptions <StorageAccountConfigurationOption>().Configure(
                options => {
                this.configuration.Bind("SecuredCredentials:StorageAccount", options);
            }
                );

            // Register the storage utility interface
            services.TryAddScoped <IStorageUtility, StorageUtility>();
            services.TryAddScoped <IKeyVaultHelper, KeyVaultHelper>();
            // Register the provisioning helper
            services.TryAddScoped <IMarketplaceNotificationHandler, ProvisioningHelper>();

            // Register the entity services
            services.TryAddScoped <IOfferService, OfferService>();
            services.TryAddScoped <IArmTemplateService, ArmTemplateService>();
            services.TryAddScoped <IPlanService, PlanService>();
            services.TryAddScoped <ISubscriptionService, SubscriptionService>();
            services.TryAddScoped <IAadSecretTmpService, AadSecretTmpService>();
            services.TryAddScoped <IArmTemplateParameterService, ArmTemplateParameterService>();
            services.TryAddScoped <ICustomMeterService, CustomMeterService>();
            services.TryAddScoped <ICustomMeterDimensionService, CustomMeterDimensionService>();
            services.TryAddScoped <IIpConfigService, IpConfigService>();
            services.TryAddScoped <IOfferParameterService, OfferParameterService>();
            services.TryAddScoped <IRestrictedUserService, RestrictedUserService>();
            services.TryAddScoped <IWebhookService, WebhookService>();
            services.TryAddScoped <IWebhookParameterService, WebhookParameterService>();
            services.TryAddScoped <IProvisioningService, ProvisioningService>();
            services.TryAddScoped <IIpAddressService, IpAddressService>();
            services.TryAddScoped <ISubscriptionParameterService, SubscriptionParameterService>();
            services.TryAddScoped <IWebhookWebhookParameterService, WebhookWebhookParameterService>();
            services.TryAddScoped <IArmTemplateArmTemplateParameterService, ArmTemplateArmTemplateParameterService>();
            services.TryAddScoped <ITelemetryDataConnectorService, TelemetryDataConnectorService>();
            services.TryAddScoped <ISubscriptionCustomMeterUsageService, SubscriptionCustomMeterUsageService>();

            services.TryAddScoped <ICustomMeterEventService, CustomMeterEventService>();
            // Register luna db client
            services.AddHttpClient("Luna", x => { x.BaseAddress = new Uri(configuration.GetValue <string>("LunaClient:BaseUri")); });
            services.TryAddScoped <LunaClient>();


            services.AddCors();

            services.AddRazorPages();

            services.AddApiVersioning(o => {
                DateTime groupVersion = DateTime.ParseExact(apiVersion, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
                ApiVersion latest     = new ApiVersion(groupVersion);

                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = latest;

                o.Conventions.Controller <OfferController>().HasApiVersion(latest);
                o.Conventions.Controller <ArmTemplateController>().HasApiVersion(latest);
                o.Conventions.Controller <PlanController>().HasApiVersion(latest);
                o.Conventions.Controller <SubscriptionController>().HasApiVersion(latest);
                o.Conventions.Controller <ArmTemplateParameterController>().HasApiVersion(latest);
                o.Conventions.Controller <CustomMeterController>().HasApiVersion(latest);
                o.Conventions.Controller <CustomMeterDimensionController>().HasApiVersion(latest);
                o.Conventions.Controller <IpConfigController>().HasApiVersion(latest);
                o.Conventions.Controller <OfferParameterController>().HasApiVersion(latest);
                o.Conventions.Controller <RestrictedUserController>().HasApiVersion(latest);
                o.Conventions.Controller <WebhookController>().HasApiVersion(latest);
                o.Conventions.Controller <WebhookParameterController>().HasApiVersion(latest);
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(apiVersion, new OpenApiInfo {
                    Title = "Luna Dashboard API", Version = apiVersion
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
            services.AddApplicationInsightsTelemetry();
        }
コード例 #55
0
ファイル: TwitterApi.cs プロジェクト: hongyue/Twitter.Net
 public TwitterApi(string consumerKey, string consumerSecret, ApiVersion apiVersion = ApiVersion.V1)
     : this(consumerKey, consumerSecret, "", "", TokenType.InvalidToken, apiVersion)
 {
     
 }
コード例 #56
0
 internal virtual void OnValidate(ApiVersion version)
 {
 }
コード例 #57
0
ファイル: TwitterApi.cs プロジェクト: hongyue/Twitter.Net
        private TwitterApi(string consumerKey, string consumerSecret,
            string accessToken, string tokenSecret, TokenType tokenType, ApiVersion apiVersion = ApiVersion.V1)
        {
            var consumerCredential = new ConsumerCredential(consumerKey, consumerSecret);
            consumerCredential.SetToken(accessToken, tokenSecret, tokenType);

            var serviceProviderDescription = new ServiceProviderDescription(
                    new OAuthEndPoint("https://api.twitter.com/oauth/request_token"),
                    new OAuthEndPoint("https://api.twitter.com/oauth/authorize", HttpMethod.Get),
                    new OAuthEndPoint("https://api.twitter.com/oauth/access_token"),
                    ProtocolVersion.V10A);

            this._OAuth         = new OAuth(consumerCredential, serviceProviderDescription);
            this._OAuth.Realm   = ApiBaseUri;
            this._OAuth.Proxy   = null;

            this.ApiVersion     = apiVersion;

            this._Configuration = new TwitterConfiguration();

            this._Timer = new Timer(_ =>
                                    {
                                        var newConfig = this.RetrieveConfiguration();
                                        if (newConfig != null)
                                            Interlocked.Exchange(ref this._Configuration, newConfig);
                                    }, null, 1000, 1000 * 3600 * 24);
        }
コード例 #58
0
        /// <summary>
        /// Populates the API version parameters for the specified API description.
        /// </summary>
        /// <param name="apiDescription">The <see cref="ApiDescription">API description</see> to populate parameters for.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> used to populate parameters with.</param>
        protected virtual void PopulateApiVersionParameters(ApiDescription apiDescription, ApiVersion apiVersion)
        {
            var parameterSource = Options.ApiVersionParameterSource;
            var context         = new ApiVersionParameterDescriptionContext(apiDescription, apiVersion, modelMetadata.Value, Options);

            parameterSource.AddParameters(context);
        }
コード例 #59
0
ファイル: YsCtrl.cs プロジェクト: caideyuan/ObsidianToolkit
 protected void PrepareApiRequest(BaseAPI api, ApiVersion ver)
 {
     if (ver == ApiVersion.V2)
         api.AppKey = "webapp";
     else if(ver == ApiVersion.V3)
         api.AppKey = "webapp_v3";
 }
コード例 #60
0
        public async Task <IActionResult> CreateTransaction(CreateTransactionDto transactionDto, ApiVersion version)
        {
            var result = await _repository.CreateTransactionAsync(transactionDto);

            return(CreatedAtRoute(new { id = result.Id, version = $"{version}" }, result));
        }