Example #1
0
 private StressTestClient(ClientOptions options, List<string> serverAddresses, Dictionary<string, int> weightedTestCases)
 {
     this.options = options;
     this.serverAddresses = serverAddresses;
     this.weightedTestCases = weightedTestCases;
     this.testCaseGenerator = new WeightedRandomGenerator(this.weightedTestCases);
 }
Example #2
0
 public WebApiClientSettings(string serviceUrl, ClientOptions options = ClientOptions.Default, 
     IContentSerializer serializer = null, IClientErrorHandler errorHandler = null, Type badRequestContentType = null, Type serverErrorContentType = null)
 {
     Util.Check(!string.IsNullOrWhiteSpace(serviceUrl), "ServiceUrl may not be empty.");
       if (serviceUrl.EndsWith("/"))
     serviceUrl = serviceUrl.Substring(0, serviceUrl.Length - 1);
       ServiceUrl = serviceUrl;
       Options = options;
       Serializer = serializer ?? new JsonContentSerializer(options);
       ErrorHandler = errorHandler ?? new DefaultClientErrorHandler(Serializer, badRequestContentType, serverErrorContentType);
 }
Example #3
0
 public JsonContentSerializer(ClientOptions clientOptions, JsonSerializerSettings settings = null) {
   if (settings == null) {
     settings = new JsonSerializerSettings();
     settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); //serialize enum as names, not numbers
     settings.ContractResolver = new NodeNameContractResolver(clientOptions); //to process NodeAttribute attribute
   }
   _jsonSerializerSettings = settings;
   _serializer = JsonSerializer.Create(_jsonSerializerSettings);
   SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
   SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
   _mediaTypes.Add(JsonMediaType);
 }
Example #4
0
 internal Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
 }
 public Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider,
                      bool metricsEnabled)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
     this._metricsEnabled = metricsEnabled;
 }
Example #6
0
 internal Configuration(Policies policies,
                        ProtocolOptions protocolOptions,
                        PoolingOptions poolingOptions,
                        SocketOptions socketOptions,
                        ClientOptions clientOptions,
                        IAuthProvider authProvider,
                        IAuthInfoProvider authInfoProvider,
                        QueryOptions queryOptions)
 {
     _policies = policies;
     _protocolOptions = protocolOptions;
     _poolingOptions = poolingOptions;
     _socketOptions = socketOptions;
     _clientOptions = clientOptions;
     _authProvider = authProvider;
     _authInfoProvider = authInfoProvider;
     _queryOptions = queryOptions;
 }
Example #7
0
 public override int Execute(ClientController controller, ClientOptions options)
 {
     controller.CopyFromVM(options.Values[1], options.Values[2],
         options.Recursive, options.Force);
     return 0;
 }
Example #8
0
 /// <summary>
 /// Creates a new client under the authenticated account. Makes a POST and a GET request to the Clients resource.
 /// </summary>
 /// <param name="options">The options for the new client to be created</param>
 public Client CreateClient(ClientOptions options)
 {
     return(Execute <Client>(CreateClientRequest(options)));
 }
Example #9
0
 public ManagedInstanceAzureADOnlyAuthenticationsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null)
 {
     this.endpoint      = endpoint ?? new Uri("https://management.azure.com");
     _clientDiagnostics = clientDiagnostics;
     _pipeline          = pipeline;
     _userAgent         = HttpMessageUtilities.GetUserAgentName(this, options);
 }
        protected static IEnumerable<Type> LoadSharedDataContractTypes(
                ClientOptions proxyOptions, IContractGeneratorReferenceTypeLoader typeLoader, int targetFrameworkVersion, IList<ProxyGenerationError> importErrors)
        {
            if (typeLoader == null) throw new ArgumentNullException("typeLoader");

            // the value in sharedTypeTable is why we add this type in the shared type list. 
            // if it is only added because it is in the referenced assembly, the value will be null, otherwise it contains the entry in the type inclusion list
            // if the type is also in the exclusion list, we will report an error if the type is comming from the inclusion list, but no error if it comes from a referenced assembly only.
            Dictionary<Type, ReferencedType> sharedTypeTable = new Dictionary<Type, ReferencedType>();

            // load all types in referencedAssemblies
            IEnumerable<Assembly> referencedAssemblies = LoadReferenedAssemblies(proxyOptions, typeLoader, importErrors);
            if (referencedAssemblies != null)
            {
                foreach (Assembly referencedAssembly in referencedAssemblies)
                {
                    var typeLoader2 = typeLoader as IContractGeneratorReferenceTypeLoader2;
                    if (typeLoader2 != null)
                    {
                        foreach (Type sharedType in typeLoader2.LoadExportedTypes(referencedAssembly))
                        {
                            sharedTypeTable.Add(sharedType, null);
                        }
                    }
                    else
                    {
                        // Fall back to the original approach using IContractGeneratorReferenceTypeLoader.LoadType().
                        foreach (Type typeInAssembly in referencedAssembly.GetExportedTypes())
                        {
                            try
                            {
                                // Do multi-targeting check by calling IContractGeneratorReferenceTypeLoader.LoadType().                            
                                if (typeLoader.LoadType(typeInAssembly.FullName) != null)
                                {
                                    sharedTypeTable.Add(typeInAssembly, null);
                                }
                            }
                            catch (NotSupportedException)
                            {
                                // NotSupportedException is thrown by multi-targeting check. It's normal if some types not existing in the current FX.
                                // So we can safely ---- it.
                            }
                            catch (Exception ex)
                            {
                                // fail to load one type in an assembly: warning message
                                importErrors.Add(
                                    new ProxyGenerationError(
                                        ProxyGenerationError.GeneratorState.GenerateCode,
                                        String.Empty,
                                        ex,
                                        true));
                            }
                        }
                    }
                }
            }

            // load types in DataContractTypeList
            foreach (ReferencedType referencedType in proxyOptions.ReferencedDataContractTypeList)
            {
                try
                {
                    Type sharedType = typeLoader.LoadType(referencedType.TypeName);

                    // verify...
                    if (!IsTypeShareable(sharedType))
                    {
                        importErrors.Add(
                                new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_SharedTypeMustBePublic, referencedType.TypeName)))
                            );
                        continue;
                    }

                    sharedTypeTable[sharedType] = referencedType;
                }
                catch (Exception ex)
                {
                    importErrors.Add(new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    ex));
                }
            }

            // remove excluded types
            foreach (ReferencedType excludedType in proxyOptions.ExcludedTypeList)
            {
                try
                {
                    Type sharedType = typeLoader.LoadType(excludedType.TypeName);

                    if (sharedTypeTable.ContainsKey(sharedType))
                    {
                        if (sharedTypeTable[sharedType] != null)
                        {
                            // error message
                            importErrors.Add(new ProxyGenerationError(
                                            ProxyGenerationError.GeneratorState.GenerateCode,
                                            String.Empty,
                                            new Exception(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_DataContractExcludedAndIncluded, excludedType.TypeName))));
                        }
                        sharedTypeTable.Remove(sharedType);
                    }
                }
                catch (Exception ex)
                {
                    // waring message for excludedTypes
                    importErrors.Add(new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    ex,
                                    true));
                }
            }

            // remove unsupported types
            foreach (Type unsupportedType in GetUnsupportedTypes(targetFrameworkVersion))
            {
                sharedTypeTable.Remove(unsupportedType);
            }

            return sharedTypeTable.Keys;
        }
Example #11
0
        public static void SaveConfig(ClientOptions options)
        {
            string raw = JsonConvert.SerializeObject(options);

            File.WriteAllText(ConfigFile, raw);
        }
        public static void Run(string[] args)
        {
            var options = new ClientOptions();
            if (!Parser.Default.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            var interopClient = new InteropClient(options);
            interopClient.Run().Wait();
        }
        /// <summary>
        /// Load the list of types that we have specified as collection types in our client options.
        /// The collection types will be used to generate collections in the data contracts.
        /// </summary>
        /// <param name="proxyOptions">Options specifying the list of collection types</param>
        /// <param name="typeLoader">Type loader that resolves type names to actual CLR types</param>
        /// <param name="importErrors">Errors encountered while loading the collection types</param>
        /// <return></return>
        /// <remarks></remarks>
        protected static IEnumerable<Type> LoadSharedCollectionTypes(ClientOptions proxyOptions, IContractGeneratorReferenceTypeLoader typeLoader, IList<ProxyGenerationError> importErrors)
        {
            List<Type> referencedCollectionTypes = new List<Type>();
            foreach (ReferencedCollectionType referencedCollectionMapping in proxyOptions.CollectionMappingList)
            {
                try
                {
                    Type collectionType = typeLoader.LoadType(referencedCollectionMapping.TypeName);

                    // verify...
                    if (!IsTypeShareable(collectionType))
                    {
                        importErrors.Add(
                                new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_SharedTypeMustBePublic, referencedCollectionMapping.TypeName)))
                            );
                        continue;
                    }

                    referencedCollectionTypes.Add(collectionType);
                }
                catch (Exception ex)
                {
                    importErrors.Add(new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    ex));
                }
            }
            return referencedCollectionTypes;
        }
Example #14
0
 /// <summary>
 /// Updates a client on the authenticated account. Makes a PUT and a GET request to the Clients resource.
 /// </summary>
 /// <param name="clientId">The ID for the client to update</param>
 /// <param name="options">The options to be updated</param>
 /// <param name="cancellationToken"></param>
 public async Task <Client> UpdateClientAsync(long clientId, ClientOptions options, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await ExecuteAsync <Client>(UpdateClientRequest(clientId, options), cancellationToken));
 }
Example #15
0
 public static ValueTask ConfigOidcAsync(IJSRuntime jsRuntime, ClientOptions clientOptions)
 {
     return(jsRuntime.InvokeVoidAsync(Constants.ConfigOidc, clientOptions));
 }
 public ResponseReader(ClientOptions clientOptions, IPhysicalConnection physicalConnection)
 {
     _physicalConnection = physicalConnection;
     _clientOptions      = clientOptions;
     _buffer             = new byte[clientOptions.ConnectionOptions.ReadStreamBufferSize];
 }
Example #17
0
 public ServerAutomaticTuningRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null)
 {
     this.endpoint      = endpoint ?? new Uri("https://management.azure.com");
     _clientDiagnostics = clientDiagnostics;
     _pipeline          = pipeline;
     _userAgent         = HttpMessageUtilities.GetUserAgentName(this, options);
 }
 public static HttpPipeline Build(ClientOptions options, TokenCredential credential)
 {
     return(HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, DefaultScope)));
 }
Example #19
0
 public SqlSourceMethod(ActorSystem actorSystem, string tenant, string @namespace, string topic, long fromMessageId, long toMessageId, string brokerWebServiceUrl, ClientOptions options, HashSet <string> selectedColumns)
 {
     _actorSystem         = actorSystem;
     _fromMessageId       = fromMessageId;
     _toMessageId         = toMessageId;
     _tenant              = tenant;
     _namespace           = @namespace;
     _topic               = topic;
     _brokerWebServiceUrl = brokerWebServiceUrl;
     _options             = options;
     _selectedColumns     = selectedColumns;
 }
Example #20
0
 public void Configure(Action <ClientOptions> configure)
 {
     _spamClient.Configure(configure);
     this.Options = _spamClient.Options;
 }
Example #21
0
 /// <summary>
 /// Updates a client on the authenticated account. Makes a PUT and a GET request to the Clients resource.
 /// </summary>
 /// <param name="clientId">The ID for the client to update</param>
 /// <param name="options">The options to be updated</param>
 public Client UpdateClient(long clientId, ClientOptions options)
 {
     return(Execute <Client>(UpdateClientRequest(clientId, options)));
 }
Example #22
0
 public SocketServer(ILogger <SocketServer> logger, IOptionsMonitor <ClientOptions> clientOptions)
 {
     _logger        = logger;
     _clientOptions = clientOptions.CurrentValue;
     _listenSocket  = new Socket(SocketType.Stream, ProtocolType.Tcp);
 }
Example #23
0
        private byte[] OnGetOptions(GameSession session, byte[] body)
        {
            GetOptions request = new GetOptions();
            using(Stream stream = new MemoryStream(body)) {
                request.Deserialize(stream);
            }

            ClientOptions response = new ClientOptions();
            response.Options.Add(new PegasusUtil.ClientOption() {
                Index = 1,
                AsUint64 = 0x20FFFF3FFFCCFCFF
            });

            response.Options.Add(new PegasusUtil.ClientOption() {
                Index = 2,
                AsUint64 = 0xF0BFFFEF3FFF
            });

            response.Options.Add(new PegasusUtil.ClientOption() {
                Index = 18,
                AsUint64 = 0xB765A8C
            });

            return response.EncodeResponse(241);
        }
Example #24
0
        internal DeviceIdentity(IotHubConnectionString iotHubConnectionString, AmqpTransportSettings amqpTransportSettings, ProductInfo productInfo, ClientOptions options)
        {
            IotHubConnectionString = iotHubConnectionString;
            AmqpTransportSettings  = amqpTransportSettings;
            ProductInfo            = productInfo;
            Options = options;

            if (amqpTransportSettings.ClientCertificate == null)
            {
                Audience = CreateAudience(IotHubConnectionString);
                if (iotHubConnectionString.SharedAccessKeyName == null)
                {
                    AuthenticationModel = AuthenticationModel.SasIndividual;
                }
                else
                {
                    AuthenticationModel = AuthenticationModel.SasGrouped;
                }
            }
            else
            {
                AuthenticationModel = AuthenticationModel.X509;
            }
        }
Example #25
0
 private async Task RunTestCaseAsync(Channel channel, ClientOptions options)
 {
     var client = new TestService.TestServiceClient(channel);
     switch (options.TestCase)
     {
         case "empty_unary":
             RunEmptyUnary(client);
             break;
         case "large_unary":
             RunLargeUnary(client);
             break;
         case "client_streaming":
             await RunClientStreamingAsync(client);
             break;
         case "server_streaming":
             await RunServerStreamingAsync(client);
             break;
         case "ping_pong":
             await RunPingPongAsync(client);
             break;
         case "empty_stream":
             await RunEmptyStreamAsync(client);
             break;
         case "compute_engine_creds":
             RunComputeEngineCreds(client, options.DefaultServiceAccount, options.OAuthScope);
             break;
         case "jwt_token_creds":
             RunJwtTokenCreds(client);
             break;
         case "oauth2_auth_token":
             await RunOAuth2AuthTokenAsync(client, options.OAuthScope);
             break;
         case "per_rpc_creds":
             await RunPerRpcCredsAsync(client, options.OAuthScope);
             break;
         case "cancel_after_begin":
             await RunCancelAfterBeginAsync(client);
             break;
         case "cancel_after_first_response":
             await RunCancelAfterFirstResponseAsync(client);
             break;
         case "timeout_on_sleeping_server":
             await RunTimeoutOnSleepingServerAsync(client);
             break;
         case "custom_metadata":
             await RunCustomMetadataAsync(client);
             break;
         case "status_code_and_message":
             await RunStatusCodeAndMessageAsync(client);
             break;
         case "unimplemented_method":
             RunUnimplementedMethod(new UnimplementedService.UnimplementedServiceClient(channel));
             break;
         case "client_compressed_unary":
             RunClientCompressedUnary(client);
             break;
         case "client_compressed_streaming":
             await RunClientCompressedStreamingAsync(client);
             break;
         default:
             throw new ArgumentException("Unknown test case " + options.TestCase);
     }
 }
Example #26
0
 protected override bool CheckValues(ClientOptions options)
 {
     return Check(options.Values.Count >= 2, "Missing command to execute.");
 }
        /// <summary>
        /// Create appropriate XmlSerializerImportOptions for the generator
        /// </summary>
        /// <param name="proxyOptions">Options for the code/config generation</param>
        /// <param name="targetCompileUnit">Compile unit we are going to generate the client code in</param>
        /// <param name="codeDomProvider">CodeDom provider for the language we are using</param>
        /// <param name="proxyNamespace">CLR namespace we'll put the client code in</param>
        /// <returns></returns>
        protected static XmlSerializerImportOptions CreateXmlSerializerImportOptions(
                                ClientOptions proxyOptions,
                                CodeCompileUnit targetCompileUnit,
                                System.CodeDom.Compiler.CodeDomProvider codeDomProvider,
                                string proxyNamespace,
                                System.Type typedDataSetSchemaImporterExtension)
        {
            System.ServiceModel.Channels.XmlSerializerImportOptions xmlSerializerOptions = new XmlSerializerImportOptions(targetCompileUnit);
            System.Web.Services.Description.WebReferenceOptions webReferenceOptions = new System.Web.Services.Description.WebReferenceOptions();

            webReferenceOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties | System.Xml.Serialization.CodeGenerationOptions.GenerateOrder;

            if (proxyOptions.EnableDataBinding)
            {
                webReferenceOptions.CodeGenerationOptions |= System.Xml.Serialization.CodeGenerationOptions.EnableDataBinding;
            }

            webReferenceOptions.SchemaImporterExtensions.Add(typedDataSetSchemaImporterExtension.AssemblyQualifiedName);
            webReferenceOptions.SchemaImporterExtensions.Add(typeof(System.Data.DataSetSchemaImporterExtension).AssemblyQualifiedName);

            /* 

















*/

            xmlSerializerOptions.WebReferenceOptions = webReferenceOptions;
            xmlSerializerOptions.CodeProvider = codeDomProvider;

            xmlSerializerOptions.ClrNamespace = proxyNamespace;

            return xmlSerializerOptions;
        }
Example #28
0
 protected override bool CheckUnusedWorkingDirectory(ClientOptions options)
 {
     return true;
 }
Example #29
0
        private static void ParseArgument(string arg, ClientOptions options)
        {
            Match match;
            match = Regex.Match(arg, "--server_host=(.*)");
            if (match.Success)
            {
                options.serverHost = match.Groups[1].Value.Trim();
                return;
            }

            match = Regex.Match(arg, "--server_host_override=(.*)");
            if (match.Success)
            {
                options.serverHostOverride = match.Groups[1].Value.Trim();
                return;
            }

            match = Regex.Match(arg, "--server_port=(.*)");
            if (match.Success)
            {
                options.serverPort = int.Parse(match.Groups[1].Value.Trim());
                return;
            }

            match = Regex.Match(arg, "--test_case=(.*)");
            if (match.Success)
            {
                options.testCase = match.Groups[1].Value.Trim();
                return;
            }

            match = Regex.Match(arg, "--use_tls=(.*)");
            if (match.Success)
            {
                options.useTls = bool.Parse(match.Groups[1].Value.Trim());
                return;
            }

            match = Regex.Match(arg, "--use_test_ca=(.*)");
            if (match.Success)
            {
                options.useTestCa = bool.Parse(match.Groups[1].Value.Trim());
                return;
            }

            Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg));
            options.help = true;
        }
Example #30
0
            public override int Execute(ClientController controller, ClientOptions options)
            {
                Dictionary<string, string> environmentVariables = null;
                if (options.EnvironmentVariables != null)
                {
                    environmentVariables = new Dictionary<string, string>();
                    foreach (string v in options.EnvironmentVariables)
                    {
                        int equalsPos = v.IndexOf('=');
                        if (equalsPos < 0)
                            environmentVariables[v] = "";
                        else
                            environmentVariables[v.Substring(0, equalsPos)] = v.Substring(equalsPos + 1);
                    }
                }

                string executable = options.Values[1];
                StringBuilder arguments = new StringBuilder();
                for (int i = 2; i < options.Values.Count; i++)
                {
                    if (i != 2)
                        arguments.Append(" ");

                    string argument = options.Values[i];
                    if (ShouldArgumentBeQuoted(argument))
                        arguments.Append("\"").Append(argument).Append("\"");
                    else
                        arguments.Append(argument);
                }

                return controller.Execute(executable, arguments.ToString(), options.WorkingDirectory,
                    environmentVariables,
                    line => Console.Out.WriteLine(line),
                    line => Console.Error.WriteLine(line),
                    options.Timeout <= 0 ? (TimeSpan?)null : TimeSpan.FromSeconds(options.Timeout));
            }
Example #31
0
 /// <summary>
 /// Creates a new client under the authenticated account. Makes a POST and a GET request to the Clients resource.
 /// </summary>
 /// <param name="options">The options for the new client to be created</param>
 /// <param name="cancellationToken"></param>
 public async Task <Client> CreateClientAsync(ClientOptions options, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await ExecuteAsync <Client>(CreateClientRequest(options), cancellationToken));
 }
Example #32
0
 protected override bool CheckUnusedRecursive(ClientOptions options)
 {
     return true;
 }
 public AppicationGatewayAvailableResponseHeadersRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, string subscriptionId, Uri endpoint = null, string apiVersion = "2021-02-01")
 {
     this.subscriptionId = subscriptionId ?? throw new ArgumentNullException(nameof(subscriptionId));
     this.endpoint       = endpoint ?? new Uri("https://management.azure.com");
     this.apiVersion     = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion));
     _clientDiagnostics  = clientDiagnostics;
     _pipeline           = pipeline;
     _userAgent          = HttpMessageUtilities.GetUserAgentName(this, options);
 }
Example #34
0
 public NatClient(ClientOptions clientOptions) : base(clientOptions)
 {
 }
Example #35
0
 protected override bool CheckUnusedEnvironmentVariables(ClientOptions options)
 {
     return true;
 }
Example #36
0
 public Client(ClientOptions options)
 {
     _options = options;
     _incomingRequestHandler = new BrokerToClientRequestHandler <Task, ITransportChannel>(HandleInvocationStartRequestAsync);
 }
Example #37
0
 protected override bool CheckUnusedTimeout(ClientOptions options)
 {
     return true;
 }
Example #38
0
        internal static async Task <TransportParams> Create(string host, AblyAuth auth, ClientOptions options, string connectionKey = null, long?connectionSerial = null, ILogger logger = null)
        {
            var result = new TransportParams();

            result.Host       = host;
            result.Tls        = options.Tls;
            result.Port       = options.Tls ? options.TlsPort : options.Port;
            result.ClientId   = options.GetClientId();
            result.AuthMethod = auth.AuthMethod;
            if (result.AuthMethod == AuthMethod.Basic)
            {
                result.AuthValue = ApiKey.Parse(options.Key).ToString();
            }
            else
            {
                var token = await auth.GetCurrentValidTokenAndRenewIfNecessaryAsync();

                if (token == null)
                {
                    throw new AblyException("There is no valid token. Can't authenticate", 40100, HttpStatusCode.Unauthorized);
                }

                result.AuthValue = token.Token;
            }

            result.ConnectionKey     = connectionKey;
            result.ConnectionSerial  = connectionSerial;
            result.EchoMessages      = options.EchoMessages;
            result.FallbackHosts     = options.FallbackHosts;
            result.UseBinaryProtocol = options.UseBinaryProtocol;
            result.RecoverValue      = options.Recover;
            result.Logger            = logger ?? options.Logger;
            return(result);
        }
Example #39
0
 protected override bool CheckValues(ClientOptions options)
 {
     return Check(options.Values.Count >= 3, "Missing files to copy.")
         && Check(options.Values.Count == 3, "Found excess arguments.");
 }
 public VirtualRoutersRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null, string apiVersion = "2021-02-01")
 {
     this.endpoint      = endpoint ?? new Uri("https://management.azure.com");
     this.apiVersion    = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion));
     _clientDiagnostics = clientDiagnostics;
     _pipeline          = pipeline;
     _userAgent         = HttpMessageUtilities.GetUserAgentName(this, options);
 }
Example #41
0
 protected override bool CheckUnusedForce(ClientOptions options)
 {
     return true;
 }
Example #42
0
        private async Task RunStateMachine(CancellationToken token, ClientOptions clientOptions)
        {
            while (this.state != ClientInternalState.Terminated)
            {
                if (token.IsCancellationRequested)
                {
                    await TerminateAsync("cancellation", false);
                }

                try
                {
                    switch (this.state)
                    {
                    case ClientInternalState.NoSession:
                        var established = await EstablishSessionAsync(token);

                        switch (established)
                        {
                        case NewSessionResult.Established:
                            this.state = ClientInternalState.NoClientNode;
                            break;

                        case NewSessionResult.TimeOut:
                            this.state = ClientInternalState.NoSession;
                            await WaitRandomTime(TimeSpan.FromSeconds(5));

                            break;

                        default:
                            this.state = ClientInternalState.Error;
                            break;
                        }

                        break;

                    case ClientInternalState.NoClientNode:
                        var created = await CreateClientNodeAsync();

                        if (created)
                        {
                            this.state = ClientInternalState.NoRole;
                        }
                        else
                        {
                            this.state = ClientInternalState.Error;
                        }
                        break;

                    case ClientInternalState.NoRole:
                        var epochAttained = await CacheEpochLocallyAsync();

                        if (!epochAttained)
                        {
                            await EvaluateTerminationAsync(token, clientOptions, "Couldn't read the current epoch.");
                        }

                        var(electionResult, lowerSiblingPath) = await DetermineLeadershipAsync();

                        switch (electionResult)
                        {
                        case ElectionResult.IsLeader:
                            this.state = ClientInternalState.IsLeader;
                            this.watchSiblingNodePath = string.Empty;
                            break;

                        case ElectionResult.IsFollower:
                            this.state = ClientInternalState.IsFollower;
                            this.watchSiblingNodePath = lowerSiblingPath;
                            break;

                        default:
                            await EvaluateTerminationAsync(token, clientOptions, "The client has entered an unknown state");

                            break;
                        }

                        break;

                    case ClientInternalState.IsLeader:
                        var coordinatorExitReason = await BecomeCoordinatorAsync(token);

                        switch (coordinatorExitReason)
                        {
                        case CoordinatorExitReason.NoLongerCoordinator:
                            SetStateToNoSession();         // need a new client node
                            break;

                        case CoordinatorExitReason.Cancelled:
                            await TerminateAsync("cancellation", false);

                            break;

                        case CoordinatorExitReason.SessionExpired:
                            SetStateToNoSession();
                            break;

                        case CoordinatorExitReason.PotentialInconsistentState:
                            await EvaluateTerminationAsync(token, clientOptions, "The client has entered a potentially inconsistent state");

                            break;

                        case CoordinatorExitReason.FatalError:
                            await TerminateAsync("fatal error", true);

                            break;

                        default:
                            await EvaluateTerminationAsync(token, clientOptions, "The client has entered an unknown state");

                            break;
                        }

                        break;

                    case ClientInternalState.IsFollower:
                        var followerExitReason = await BecomeFollowerAsync(token);

                        switch (followerExitReason)
                        {
                        case FollowerExitReason.PossibleRoleChange:
                            this.state = ClientInternalState.NoRole;
                            break;

                        case FollowerExitReason.Cancelled:
                            await TerminateAsync("cancellation", false);

                            break;

                        case FollowerExitReason.SessionExpired:
                            SetStateToNoSession();
                            break;

                        case FollowerExitReason.FatalError:
                            await TerminateAsync("fatal error", true);

                            break;

                        case FollowerExitReason.PotentialInconsistentState:
                            await EvaluateTerminationAsync(token, clientOptions, "The client has entered an potential inconsistent state");

                            break;

                        default:
                            await EvaluateTerminationAsync(token, clientOptions, "The client has entered an unknown state");

                            break;
                        }

                        break;

                    case ClientInternalState.Error:
                        await EvaluateTerminationAsync(token, clientOptions, "The client has entered an error state");

                        break;

                    default:
                        await EvaluateTerminationAsync(token, clientOptions, "The client has entered an unknown state");

                        break;
                    }
                }
                catch (ZkSessionExpiredException)
                {
                    this.logger.Info(this.clientId, "ZooKeeper session lost");
                    SetStateToNoSession();
                }
                catch (ZkOperationCancelledException)
                {
                    await TerminateAsync("cancellation", false);
                }
                catch (TerminateClientException e)
                {
                    await TerminateAsync("Fatal error", true, e);
                }
                catch (InconsistentStateException e)
                {
                    await EvaluateTerminationAsync(token, clientOptions, "An error has caused that may have left the client in an inconsistent state.", e);
                }
                catch (Exception e)
                {
                    await EvaluateTerminationAsync(token, clientOptions, "An unexpected error has been caught", e);
                }
            }
        }
Example #43
0
        public static void Run(string[] args)
        {
            var options = new ClientOptions();
            if (!Parser.Default.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            GrpcPreconditions.CheckArgument(options.NumChannelsPerServer > 0);
            GrpcPreconditions.CheckArgument(options.NumStubsPerChannel > 0);

            var serverAddresses = options.ServerAddresses.Split(',');
            GrpcPreconditions.CheckArgument(serverAddresses.Length > 0, "You need to provide at least one server address");

            var testCases = ParseWeightedTestCases(options.TestCases);
            GrpcPreconditions.CheckArgument(testCases.Count > 0, "You need to provide at least one test case");

            var interopClient = new StressTestClient(options, serverAddresses.ToList(), testCases);
            interopClient.Run().Wait();
        }
 public ManagedDatabaseSecurityEventsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null)
 {
     this.endpoint      = endpoint ?? new Uri("https://management.azure.com");
     _clientDiagnostics = clientDiagnostics;
     _pipeline          = pipeline;
     _userAgent         = HttpMessageUtilities.GetUserAgentName(this, options);
 }
Example #45
0
 public static bool IsSet(this ClientOptions options, ClientOptions option)
 {
     return (options & option) != 0;
 }
        public static HttpPipeline BuildHttpPipeline(this ClientOptions options, ConnectionString connectionString)
        {
            var authPolicy = new HMACAuthenticationPolicy(new AzureKeyCredential(connectionString.GetRequired("accesskey")));

            return(HttpPipelineBuilder.Build(options, authPolicy));
        }
Example #47
0
 private async Task RunTestCaseAsync(TestService.TestServiceClient client, ClientOptions options)
 {
     switch (options.TestCase)
     {
         case "empty_unary":
             RunEmptyUnary(client);
             break;
         case "large_unary":
             RunLargeUnary(client);
             break;
         case "client_streaming":
             await RunClientStreamingAsync(client);
             break;
         case "server_streaming":
             await RunServerStreamingAsync(client);
             break;
         case "ping_pong":
             await RunPingPongAsync(client);
             break;
         case "empty_stream":
             await RunEmptyStreamAsync(client);
             break;
         case "compute_engine_creds":
             RunComputeEngineCreds(client, options.DefaultServiceAccount, options.OAuthScope);
             break;
         case "jwt_token_creds":
             RunJwtTokenCreds(client, options.DefaultServiceAccount);
             break;
         case "oauth2_auth_token":
             await RunOAuth2AuthTokenAsync(client, options.DefaultServiceAccount, options.OAuthScope);
             break;
         case "per_rpc_creds":
             await RunPerRpcCredsAsync(client, options.DefaultServiceAccount, options.OAuthScope);
             break;
         case "cancel_after_begin":
             await RunCancelAfterBeginAsync(client);
             break;
         case "cancel_after_first_response":
             await RunCancelAfterFirstResponseAsync(client);
             break;
         case "timeout_on_sleeping_server":
             await RunTimeoutOnSleepingServerAsync(client);
             break;
         case "benchmark_empty_unary":
             RunBenchmarkEmptyUnary(client);
             break;
         default:
             throw new ArgumentException("Unknown test case " + options.TestCase);
     }
 }
        public static HttpPipeline BuildHttpPipeline(this ClientOptions options, AzureKeyCredential keyCredential)
        {
            var authPolicy = new HMACAuthenticationPolicy(keyCredential);

            return(HttpPipelineBuilder.Build(options, authPolicy));
        }
        public static HttpPipeline BuildHttpPipeline(this ClientOptions options, TokenCredential tokenCredential)
        {
            var authPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, "https://communication.azure.com//.default");

            return(HttpPipelineBuilder.Build(options, authPolicy));
        }
Example #50
0
 private InteropClient(ClientOptions options)
 {
     this.options = options;
 }
        /// <summary>
        /// Load referenced assemblies
        /// </summary>
        /// <param name="proxyOptions"></param>
        /// <param name="typeLoader"></param>
        /// <param name="importErrors"></param>
        /// <return></return>
        /// <remarks></remarks>
        private static IEnumerable<Assembly> LoadReferenedAssemblies(ClientOptions proxyOptions, IContractGeneratorReferenceTypeLoader typeLoader, IList<ProxyGenerationError> importErrors)
        {
            List<Assembly> referencedAssemblies = new List<Assembly>();
            if (proxyOptions.ReferenceAllAssemblies)
            {
                try
                {
                    IEnumerable<Exception> loadingErrors = null;
                    IEnumerable<Assembly> allAssemblies = null;
                    typeLoader.LoadAllAssemblies(out allAssemblies, out loadingErrors);
                    if (loadingErrors != null)
                    {
                        // treat as warning messages
                        foreach (Exception ex in loadingErrors)
                        {
                            importErrors.Add(new ProxyGenerationError(
                                            ProxyGenerationError.GeneratorState.GenerateCode,
                                            String.Empty,
                                            ex,
                                            true));
                        }
                    }

                    if (allAssemblies != null)
                    {
                        referencedAssemblies.AddRange(allAssemblies);
                    }
                }
                catch (Exception ex)
                {
                    importErrors.Add(new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    ex));
                }
            }

            foreach (ReferencedAssembly referencedAssembly in proxyOptions.ReferencedAssemblyList)
            {
                try
                {
                    Assembly refAssembly = typeLoader.LoadAssembly(referencedAssembly.AssemblyName);
                    if (refAssembly != null && !referencedAssemblies.Contains(refAssembly))
                    {
                        referencedAssemblies.Add(refAssembly);
                    }
                }
                catch (Exception ex)
                {
                    importErrors.Add(new ProxyGenerationError(
                                    ProxyGenerationError.GeneratorState.GenerateCode,
                                    String.Empty,
                                    ex));
                }
            }
            return referencedAssemblies;
        }
Example #52
0
 protected RestClient(ClientOptions exchangeOptions, AuthenticationProvider authenticationProvider) : base(exchangeOptions, authenticationProvider)
 {
     Configure(exchangeOptions);
 }
        /// <summary>
        /// Instantiate and configure a ServiceContractGenerator to be used for code and config
        /// generation.
        /// </summary>
        /// <param name="proxyOptions">
        /// Options set in the SvcMap file to control the code/config generation.
        /// </param>
        /// <param name="wsdlImporter">
        /// The WsdlImporter that is to be used to import the metadata for this service reference.
        /// </param>
        /// <param name="targetCompileUnit">
        /// Compile unit into which we will generate the client code
        /// </param>
        /// <param name="proxyNamespace">
        /// The CLR namespace into which we will generate the client code.
        /// </param>
        /// <param name="targetConfiguration">
        /// Optional configuration into which we will generate the endpoints/bindings corresponding
        /// to this service reference. May be Null/Nothing, in which case we will not generate config.
        /// </param>
        /// <param name="typeLoader">
        /// Type loader that can be used to find reference assemblies and/or resolve shared service and
        /// data contract types.
        /// </param>
        /// <param name="targetFrameworkVersion">
        /// The target framework version number. The higher 16 bits contains the major version number, and low 16 bits contains minor version number.
        /// </param>
        /// <param name="importErrors">
        /// The list into which we will add any errors while importing the metadata.
        /// </param>
        /// <returns></returns>
        protected static ServiceContractGenerator CreateContractGenerator(ClientOptions proxyOptions,
                                            WsdlImporter wsdlImporter,
                                            CodeCompileUnit targetCompileUnit,
                                            string proxyNamespace,
                                            System.Configuration.Configuration targetConfiguration,
                                            IContractGeneratorReferenceTypeLoader typeLoader,
                                            int targetFrameworkVersion,
                                            IList<ProxyGenerationError> importErrors)
        {
            ServiceContractGenerator contractGenerator = new ServiceContractGenerator(targetCompileUnit, targetConfiguration);

            // We want to generate all types into the proxy namespace CLR namespace. We indicate
            // this by adding a namespace mapping from all XML namespaces ("*") to the namespace
            // the caller told us to generate the client code in.
            contractGenerator.NamespaceMappings.Add("*", proxyNamespace);

            if (proxyOptions.GenerateInternalTypes)
            {
                contractGenerator.Options |= ServiceContractGenerationOptions.InternalTypes;
            }
            else
            {
                contractGenerator.Options &= ~ServiceContractGenerationOptions.InternalTypes;
            }

            // Make sure at most one of the async options will be set: AsynchronousMethods | TaskBasedAsynchronousMethod.
            contractGenerator.Options &= ~ServiceContractGenerationOptions.AsynchronousMethods &
                                         ~ServiceContractGenerationOptions.EventBasedAsynchronousMethods &
                                         ~ServiceContractGenerationOptions.TaskBasedAsynchronousMethod;

            if (proxyOptions.GenerateTaskBasedAsynchronousMethod)
            {
                contractGenerator.Options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod;
            }
            else if (proxyOptions.GenerateAsynchronousMethods)
            {
                contractGenerator.Options |= ServiceContractGenerationOptions.AsynchronousMethods;
                if (targetFrameworkVersion >= FRAMEWORK_VERSION_35)
                {
                    contractGenerator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods;
                }
            }

            if (proxyOptions.GenerateMessageContracts)
            {
                contractGenerator.Options |= ServiceContractGenerationOptions.TypedMessages;
            }
            else
            {
                contractGenerator.Options &= ~ServiceContractGenerationOptions.TypedMessages;
            }

            // If we have a type loader, we tell the contract generator and wsdl importer about
            // all shared types and assemblies that we've specified in the proxy options...
            if (typeLoader != null)
            {
                foreach (ContractMapping mapping in proxyOptions.ServiceContractMappingList)
                {
                    try
                    {
                        Type sharedType = typeLoader.LoadType(mapping.TypeName);

                        // verify that the type is shareable - if not, we generate an error...
                        if (!IsTypeShareable(sharedType))
                        {
                            importErrors.Add(
                                    new ProxyGenerationError(
                                        ProxyGenerationError.GeneratorState.GenerateCode,
                                        String.Empty,
                                        new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_SharedTypeMustBePublic, mapping.TypeName)))
                                );
                            continue;
                        }

                        // Get a contract description corresponding to the type we wanted to share
                        ContractDescription contract = ContractDescription.GetContract(sharedType);

                        if (!String.Equals(mapping.Name, contract.Name, StringComparison.Ordinal) ||
                                !String.Equals(mapping.TargetNamespace, contract.Namespace, StringComparison.Ordinal))
                        {
                            // mismatch
                            importErrors.Add(
                                    new ProxyGenerationError(
                                        ProxyGenerationError.GeneratorState.GenerateCode,
                                        String.Empty,
                                        new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_ServiceContractMappingMissMatch, mapping.TypeName, contract.Namespace, contract.Name, mapping.TargetNamespace, mapping.Name)))
                                );
                        }

                        XmlQualifiedName qname = new XmlQualifiedName(contract.Name, contract.Namespace);
                        wsdlImporter.KnownContracts.Add(qname, contract);
                        contractGenerator.ReferencedTypes.Add(contract, sharedType);
                    }
                    catch (Exception ex)
                    {
                        importErrors.Add(new ProxyGenerationError(
                                        ProxyGenerationError.GeneratorState.GenerateCode,
                                        String.Empty,
                                        ex));
                    }
                }
            }

            foreach (NamespaceMapping namespaceMapping in proxyOptions.NamespaceMappingList)
            {
                contractGenerator.NamespaceMappings.Add(namespaceMapping.TargetNamespace, namespaceMapping.ClrNamespace);
            }

            return contractGenerator;
        }
Example #54
0
        private async Task RunTestCaseAsync(IChannelWrapper channel, ClientOptions options)
        {
            var client = CreateClient <TestService.TestServiceClient>(channel);

            switch (options.TestCase)
            {
            case "empty_unary":
                RunEmptyUnary(client);
                break;

            case "large_unary":
                RunLargeUnary(client);
                break;

            case "client_streaming":
                await RunClientStreamingAsync(client);

                break;

            case "server_streaming":
                await RunServerStreamingAsync(client);

                break;

            case "ping_pong":
                await RunPingPongAsync(client);

                break;

            case "empty_stream":
                await RunEmptyStreamAsync(client);

                break;

            case "compute_engine_creds":
                RunComputeEngineCreds(client, options.DefaultServiceAccount !, options.OAuthScope !);
                break;

            case "jwt_token_creds":
                RunJwtTokenCreds(client);
                break;

            case "oauth2_auth_token":
                await RunOAuth2AuthTokenAsync(client, options.OAuthScope !);

                break;

            case "per_rpc_creds":
                await RunPerRpcCredsAsync(client, options.OAuthScope !);

                break;

            case "cancel_after_begin":
                await RunCancelAfterBeginAsync(client);

                break;

            case "cancel_after_first_response":
                await RunCancelAfterFirstResponseAsync(client);

                break;

            case "timeout_on_sleeping_server":
                await RunTimeoutOnSleepingServerAsync(client);

                break;

            case "custom_metadata":
                await RunCustomMetadataAsync(client);

                break;

            case "status_code_and_message":
                await RunStatusCodeAndMessageAsync(client);

                break;

            case "unimplemented_service":
                RunUnimplementedService(CreateClient <UnimplementedService.UnimplementedServiceClient>(channel));
                break;

            case "special_status_message":
                await RunSpecialStatusMessageAsync(client);

                break;

            case "unimplemented_method":
                RunUnimplementedMethod(client);
                break;

            case "client_compressed_unary":
                RunClientCompressedUnary(client);
                break;

            case "client_compressed_streaming":
                await RunClientCompressedStreamingAsync(client);

                break;

            case "server_compressed_unary":
                await RunServerCompressedUnary(client);

                break;

            case "server_compressed_streaming":
                await RunServerCompressedStreamingAsync(client);

                break;

            default:
                throw new ArgumentException("Unknown test case " + options.TestCase);
            }
        }
        /// <summary>
        /// Create an appropriate XsdDataContractImporter for the generator
        /// </summary>
        /// <param name="proxyOptions">Code/config generation options to use</param>
        /// <param name="targetCompileUnit">CodeCompileUnit into which we will generate the client code</param>
        /// <param name="codeDomProvider">CodeDomProvider for the language we will use to generate the client</param>
        /// <param name="proxyNamespace">CLR namespace in which the client code will be generated</param>
        /// <param name="typeLoader">Service used to resolve type/assembly names (strings) to actual Types and Assemblies</param>
        /// <param name="targetFrameworkVersion">Targetted Framework version number</param>
        /// <param name="importErrors">List of errors encountered. New errors will be added to this list</param>
        /// <returns></returns>
        protected static XsdDataContractImporter CreateDataContractImporter(
                ClientOptions proxyOptions,
                CodeCompileUnit targetCompileUnit,
                System.CodeDom.Compiler.CodeDomProvider codeDomProvider,
                string proxyNamespace,
                IContractGeneratorReferenceTypeLoader typeLoader,
                int targetFrameworkVersion,
                IList<ProxyGenerationError> importErrors)
        {
            System.Runtime.Serialization.XsdDataContractImporter xsdDataContractImporter = new System.Runtime.Serialization.XsdDataContractImporter(targetCompileUnit);
            System.Runtime.Serialization.ImportOptions options = new System.Runtime.Serialization.ImportOptions();

            options.CodeProvider = codeDomProvider;

            // We specify that we want to generate all types from all XML namespaces into
            // our proxy namespace. By default, each XML namespace get's its own CLR namespace
            options.Namespaces.Add("*", proxyNamespace);
            options.GenerateInternal = proxyOptions.GenerateInternalTypes;
            options.GenerateSerializable = proxyOptions.GenerateSerializableTypes;
            options.EnableDataBinding = proxyOptions.EnableDataBinding;
            options.ImportXmlType = proxyOptions.ImportXmlTypes;

            if (typeLoader != null)
            {
                IEnumerable<Type> referencedTypes = LoadSharedDataContractTypes(proxyOptions, typeLoader, targetFrameworkVersion, importErrors);
                if (referencedTypes != null)
                {
                    foreach (Type sharedType in referencedTypes)
                    {
                        options.ReferencedTypes.Add(sharedType);
                    }
                }

                IEnumerable<Type> referencedCollectionTypes = LoadSharedCollectionTypes(proxyOptions, typeLoader, importErrors);
                if (referencedCollectionTypes != null)
                {
                    foreach (Type collectionType in referencedCollectionTypes)
                    {
                        options.ReferencedCollectionTypes.Add(collectionType);
                    }
                }

            }

            foreach (NamespaceMapping namespaceMapping in proxyOptions.NamespaceMappingList)
            {
                options.Namespaces.Add(namespaceMapping.TargetNamespace, namespaceMapping.ClrNamespace);
            }

            xsdDataContractImporter.Options = options;

            return xsdDataContractImporter;
        }
 public SteamfitterService(IHttpContextAccessor httpContextAccessor, ClientOptions clientSettings, ISteamfitterApiClient steamfitterApiClient)
 {
     _userId = httpContextAccessor.HttpContext.User.GetId();
     _steamfitterApiClient = steamfitterApiClient;
 }
Example #57
0
 private static ClientOptions ParseArguments(string[] args)
 {
     var options = new ClientOptions();
     foreach (string arg in args)
     {
         ParseArgument(arg, options);
         if (options.help)
         {
             break;
         }
     }
     return options;
 }
Example #58
0
 public PrivateEndpointConnectionsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, string subscriptionId, Uri endpoint = null)
 {
     this.subscriptionId = subscriptionId ?? throw new ArgumentNullException(nameof(subscriptionId));
     this.endpoint       = endpoint ?? new Uri("https://management.azure.com");
     _clientDiagnostics  = clientDiagnostics;
     _pipeline           = pipeline;
     _userAgent          = HttpMessageUtilities.GetUserAgentName(this, options);
 }
Example #59
0
 private InteropClient(ClientOptions options)
 {
     this.options = options;
 }
Example #60
0
        public override void HandleInput(InputState input)
        {
            if (input.IsNewKeyPress(Keys.Up))
            {
                if (!ResolutionActive)
                {
                    SelectedEntry--;

                    if (SelectedEntry < 0)
                    {
                        SelectedEntry = MenuEntries.Count - 1;
                    }
                }
                else if (ResolutionActive)
                {
                    ResolutionSelectedEntry--;

                    if (ResolutionSelectedEntry < 0)
                    {
                        ResolutionSelectedEntry = ResolutionEntries.Count - 1;
                    }
                }
            }
            if (input.IsNewKeyPress(Keys.Down))
            {
                if (!ResolutionActive)
                {
                    SelectedEntry++;

                    if (SelectedEntry >= MenuEntries.Count)
                    {
                        SelectedEntry = 0;
                    }
                }
                else if (ResolutionActive)
                {
                    ResolutionSelectedEntry++;

                    if (ResolutionSelectedEntry >= ResolutionEntries.Count)
                    {
                        ResolutionSelectedEntry = 0;
                    }
                }
            }
            if (input.IsNewKeyPress(Keys.Enter))
            {
                switch (SelectedEntry)
                {
                case (int)OptionsEntry.Resolution:
                    if (ResolutionActive)
                    {
                        Resolution res = Resolutions[ResolutionSelectedEntry];
                        this.ScreenManager.Graphics.PreferredBackBufferWidth  = res.Width;
                        this.ScreenManager.Graphics.PreferredBackBufferHeight = res.Height;
                        ClientOptions.SetResolution(res.Height, res.Width);

                        ResolutionChanged = true;
                        ResolutionActive  = false;
                    }
                    else if (!ResolutionActive)
                    {
                        ResolutionActive = true;
                    }
                    break;

                case (int)OptionsEntry.Fullscreen:
                    if (ClientOptions.Fullscreen)
                    {
                        this.ScreenManager.Graphics.ToggleFullScreen();
                        ClientOptions.SetFullscreen(false);
                    }
                    else
                    {
                        this.ScreenManager.Graphics.ToggleFullScreen();
                        ClientOptions.SetFullscreen(true);
                    }
                    FullscreenChanged = true;
                    break;

                case (int)OptionsEntry.Exit:
                    ClientOptions.Save();     // save client options
                    ScreenManager.RemoveScreen(this);
                    ParentScreen.CurrentScreenState = ScreenState.Active;
                    break;
                }
            }
            if (input.IsNewKeyPress(Keys.Escape))
            {
                if (ResolutionActive)
                {
                    ResolutionActive = false;
                }
                else
                {
                    ClientOptions.Save();
                    ScreenManager.RemoveScreen(this);
                    ParentScreen.CurrentScreenState = ScreenState.Active;
                }
            }
        }