System.Net.WebUtility.UrlEncode(string)

Here are the examples of the csharp api System.Net.WebUtility.UrlEncode(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

538 Examples 7

19 View Source File : Example.cs
License : MIT License
Project Creator : Azure

public async Task GetAsync()
        {
            var request = new HttpRequest();

            try
            {
                request.SetUriFromString("https://192.168.0.1/v1/data?key=" + WebUtility.UrlEncode("some parameter"));
                request.AddHeader("X-Foo", "Bar");
                request.Options.Timeout = 5 * 1000;
                request.Options.AllowInsecureSSLServer = true;
                request.Options.EnsureSuccess = true;
                var response = await this.httpClient.GetAsync(request);

                Console.WriteLine(response.Content);
                Console.WriteLine(response.Headers.ETag);
                Console.WriteLine(response.StatusCode);
            }
            catch (HttpRequestException e)
            {
                this.log.Error("Request failed", () => new
                {
                    request.Uri,
                    e.Message
                });
                throw;
            }
        }

19 View Source File : DefaultServiceEndpointGenerator.cs
License : MIT License
Project Creator : Azure

public string GetClientEndpoint(string hubName, string applicationName, string originalPath, string queryString)
        {
            var queryBuilder = new StringBuilder();
            if (!string.IsNullOrEmpty(originalPath))
            {
                queryBuilder.Append("&")
                    .Append(Constants.QueryParameter.OriginalPath)
                    .Append("=")
                    .Append(WebUtility.UrlEncode(originalPath));
            }

            if (!string.IsNullOrEmpty(queryString))
            {
                queryBuilder.Append("&").Append(queryString);
            }

            return $"{InternalGetUri(ClientPath, hubName, applicationName, ClientEndpoint)}{queryBuilder}";
        }

19 View Source File : NegotiateHandler.cs
License : MIT License
Project Creator : Azure

private string GetQueryString(string originalQueryString, string cultureName)
        {
            var clientRequestId = _connectionRequestIdProvider.GetRequestId();
            if (clientRequestId != null)
            {
                clientRequestId = WebUtility.UrlEncode(clientRequestId);
            }

            var queryString = $"{Constants.QueryParameter.ConnectionRequestId}={clientRequestId}";
            if (!string.IsNullOrEmpty(cultureName))
            {
                queryString += $"&{Constants.QueryParameter.RequestCulture}={cultureName}";
            }

            return originalQueryString != null
                ? $"{originalQueryString}&{queryString}"
                : queryString;
        }

19 View Source File : ServiceEndpointProvider.cs
License : MIT License
Project Creator : Azure

public string GetClientEndpoint(string hubName = null, string originalPath = null, string queryString = null)
        {
            var queryBuilder = new StringBuilder();

            if (!string.IsNullOrEmpty(queryString))
            {
                queryBuilder.Append(queryString);
            }

            if (!string.IsNullOrEmpty(originalPath))
            {
                if (queryBuilder.Length == 0)
                {
                    queryBuilder.Append("?");
                }
                else
                {
                    queryBuilder.Append("&");
                }

                queryBuilder
                    .Append(Constants.QueryParameter.OriginalPath)
                    .Append("=")
                    .Append(WebUtility.UrlEncode(originalPath));
            }

            return $"{_clientEndpoint}/{ClientPath}{queryBuilder}";
        }

19 View Source File : ConnectionFactory.cs
License : MIT License
Project Creator : Azure

private Uri GetServiceUrl(IServiceEndpointProvider provider, string hubName, string connectionId, string target)
        {
            var baseUri = new UriBuilder(provider.GetServerEndpoint(hubName));
            var query = "cid=" + connectionId;
            if (target != null)
            {
                query = $"{query}&target={WebUtility.UrlEncode(target)}";
            }
            if (baseUri.Query != null && baseUri.Query.Length > 1)
            {
                baseUri.Query = baseUri.Query.Substring(1) + "&" + query;
            }
            else
            {
                baseUri.Query = query;
            }
            return baseUri.Uri;
        }

19 View Source File : ServiceConnectionFacts.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task ServiceConnectionStartsConnection()
        {
            var connectionId1 = Guid.NewGuid().ToString("N");
            var connectionId2 = Guid.NewGuid().ToString("N");

            var proxy = new ServiceConnectionProxy();

            var serverTask = proxy.WaitForServerConnectionAsync(1);
            _ = proxy.StartAsync();
            await serverTask.OrTimeout();

            replacedert.Empty(proxy.ClientConnectionManager.ClientConnections);

            // Wait for the connection to appear, we need to do this before
            // sending the message to avoid races
            var connection1Task = proxy.WaitForConnectionAsync(connectionId1);

            // Create a new client connection
            await proxy.WriteMessageAsync(new OpenConnectionMessage(connectionId1, null));

            var connection1 = await connection1Task.OrTimeout();

            replacedert.Single(proxy.ClientConnectionManager.ClientConnections);

            var httpContext1 = connection1.GetHttpContext();
            replacedert.NotNull(httpContext1);
            replacedert.Empty(httpContext1.Request.Headers);
            replacedert.Empty(httpContext1.Request.Query);
            replacedert.Equal(string.Empty, httpContext1.Request.Path);

            // Wait for the connection to appear
            var connectionTask2 = proxy.WaitForConnectionAsync(connectionId2);

            // Create another client connection
            const string headerKey1 = "custom-header-1";
            const string headerValue1 = "custom-value-1";
            const string headerKey2 = "custom-header-2";
            var headerValue2 = new[] { "custom-value-2a", "custom-value-2b" };
            const string headerKey3 = "custom-header-3";
            var headerValue3 = new[] { "custom-value-3a", "custom-value-3b", "custom-value-3c" };
            const string path = "/this/is/user/path";

            await proxy.WriteMessageAsync(new OpenConnectionMessage(connectionId2, null,
                new Dictionary<string, StringValues>
                {
                    {headerKey1, headerValue1},
                    {headerKey2, headerValue2},
                    {headerKey3, headerValue3}
                },
                $"?customQuery1=customValue1&customQuery2=customValue2&{Constants.QueryParameter.OriginalPath}={WebUtility.UrlEncode(path)}"));

            var connection2 = await connectionTask2.OrTimeout();

            replacedert.Equal(2, proxy.ClientConnectionManager.ClientConnections.Count);

            var httpContext2 = connection2.GetHttpContext();
            replacedert.NotNull(httpContext2);
            replacedert.Equal(3, httpContext2.Request.Headers.Count);
            replacedert.Equal(headerValue1, httpContext2.Request.Headers[headerKey1]);
            replacedert.Equal(headerValue2, httpContext2.Request.Headers[headerKey2]);
            replacedert.Equal(headerValue3, httpContext2.Request.Headers[headerKey3]);
            replacedert.Equal(3, httpContext2.Request.Query.Count);
            replacedert.Equal("customValue1", httpContext2.Request.Query["customQuery1"]);
            replacedert.Equal("customValue2", httpContext2.Request.Query["customQuery2"]);
            replacedert.Equal(path, httpContext2.Request.Query[Constants.QueryParameter.OriginalPath]);
            replacedert.Equal(path, httpContext2.Request.Path);

            // Send a message to client 1
            await proxy.WriteMessageAsync(new ConnectionDataMessage(connectionId1, Encoding.ASCII.GetBytes("Hello")));

            var item = await connection1.Transport.Input.ReadSingleAsync().OrTimeout();

            replacedert.Equal("Hello", Encoding.ASCII.GetString(item));

            var connection1CloseTask = proxy.WaitForConnectionCloseAsync(connectionId1);

            // Close client 1
            await proxy.WriteMessageAsync(new CloseConnectionMessage(connectionId1, null));

            await connection1CloseTask.OrTimeout();

            replacedert.Single(proxy.ClientConnectionManager.ClientConnections);

            // Close client 2
            var connection2CloseTask = proxy.WaitForConnectionCloseAsync(connectionId2);

            await proxy.WriteMessageAsync(new CloseConnectionMessage(connectionId2, null));

            await connection2CloseTask.OrTimeout();

            replacedert.Empty(proxy.ClientConnectionManager.ClientConnections);

            proxy.Stop();
        }

19 View Source File : ServiceContextFacts.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void ServiceConnectionContextWithRequestPath()
        {
            const string path = "/this/is/user/path";
            var queryString = $"?{Constants.QueryParameter.OriginalPath}={WebUtility.UrlEncode(path)}";
            var serviceConnectionContext = new ClientConnectionContext(new OpenConnectionMessage("1", null, EmptyHeaders, queryString));

            replacedert.NotNull(serviceConnectionContext.User.Idenreplacedy);
            replacedert.NotNull(serviceConnectionContext.HttpContext);
            replacedert.Equal(serviceConnectionContext.User, serviceConnectionContext.HttpContext.User);
            var request = serviceConnectionContext.HttpContext.Request;
            replacedert.Empty(request.Headers);
            replacedert.Equal(1, request.Query.Count);
            replacedert.Equal(path, request.Query[Constants.QueryParameter.OriginalPath]);
            replacedert.Equal(path, request.Path);
        }

19 View Source File : VideoIndexerService.cs
License : MIT License
Project Creator : Azure

public async Task<VideoIndexerSearchResult> SearchAsync(string query = "", string face = "")
        {
            if (string.IsNullOrEmpty(query) == true && string.IsNullOrEmpty(face) == true)
            {
                return default(VideoIndexerSearchResult);
            }

            Dictionary<string, string> queryParams = new Dictionary<string, string>()
            {
                { "query", WebUtility.UrlEncode(query) },
                { "face", WebUtility.UrlEncode(face) },
            };

            IEnumerable<string> queryString = queryParams
                .Where(p => string.IsNullOrEmpty(p.Value) == false)
                .Select(p => p.Key + "=" + p.Value);

            string searchQuery = queryString.Count() == 1 ? queryString.FirstOrDefault() : string.Join("&", queryString);

            // Get request uri
            string searchUrl = this.BaseServiceUrl + "?" + searchQuery;
            Uri requestUri = new Uri(searchUrl);

            // Get response
            VideoIndexerSearchResult result = await HttpClientUtility.GetAsync<VideoIndexerSearchResult>(requestUri, this.RequestHeaders);
            return result;
        }

19 View Source File : LUISService.cs
License : MIT License
Project Creator : Azure

public async Task<LUISResult> QueryAsync(string query)
        {
            if (string.IsNullOrEmpty(query) == true)
            {
                return default(LUISResult);
            }

            query = WebUtility.UrlEncode(query);

            // Get request uri
            string requestUrl = this.BaseServiceUrl + "&verbose=true&timezoneOffset=0&q=" + query;
            Uri requestUri = new Uri(requestUrl);

            LUISResult result = await HttpClientUtility.GetAsync<LUISResult>(requestUri, this.RequestHeaders);
            return result;
        }

19 View Source File : BingSearchService.cs
License : MIT License
Project Creator : Azure

public async Task<BingWebSearchResult> SearchWebAsync(string query, int count = 10, int offset = 0, string market = "en-us", SafeSearch safeSearch = SafeSearch.Strict)
        {
            if (string.IsNullOrEmpty(query) == true)
            {
                return default(BingWebSearchResult);
            }
            else if (query.Length > MAX_QUERY_LENGTH)
            {
                query = query.Substring(0, MAX_QUERY_LENGTH);
            }

            query = WebUtility.UrlEncode(query);

            // Get request uri
            string searchUrl = string.Format(this.BaseServiceUrl + "search?q={0}&count={1}&offset={2}&mkt={3}&safesearch={4}", query, count, offset, market, safeSearch);
            Uri requestUri = new Uri(searchUrl);

            // Get response
            BingWebSearchResult result = await HttpClientUtility.GetAsync<BingWebSearchResult>(requestUri, this.RequestHeaders);
            return result;
        }

19 View Source File : CommonModule.cs
License : MIT License
Project Creator : Azure

protected override void Load(ContainerBuilder builder)
        {
            // IMetricsListener
            builder.Register(
                    c =>
                        this.metricsConfig.Enabled
                            ? new MetricsListener(this.metricsConfig.ListenerConfig, c.Resolve<IMetricsProvider>())
                            : new NullMetricsListener() as IMetricsListener)
                .As<IMetricsListener>()
                .SingleInstance();

            // IMetricsProvider
            builder.Register(
                    c =>
                        this.metricsConfig.Enabled
                            ? new MetricsProvider(MetricsConstants.EdgeHubMetricPrefix, this.iothubHostName, this.edgeDeviceId, this.metricsConfig.HistogramMaxAge)
                            : new NullMetricsProvider() as IMetricsProvider)
                .As<IMetricsProvider>()
                .SingleInstance();

            // ISignatureProvider
            builder.Register(
                    c =>
                    {
                        ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map(
                                cs =>
                                {
                                    IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs);
                                    return new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider;
                                })
                            .GetOrElse(
                                () =>
                                {
                                    string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing"));
                                    string workloadUri = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing"));
                                    string workloadApiVersion = this.workloadApiVersion.Expect(() => new InvalidOperationException("workloadUri version is missing"));
                                    return new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, workloadApiVersion, Constants.WorkloadApiVersion) as ISignatureProvider;
                                });
                        return signatureProvider;
                    })
                .As<ISignatureProvider>()
                .SingleInstance();

            // Detect system environment
            builder.Register(c => new SystemEnvironment())
                .As<ISystemEnvironment>()
                .SingleInstance();

            // DataBase options
            builder
                .Register(c => new RocksDbOptionsProvider(
                    c.Resolve<ISystemEnvironment>(),
                    this.optimizeForPerformance,
                    this.storageMaxTotalWalSize,
                    this.storageMaxManifestFileSize,
                    this.storageMaxOpenFiles,
                    this.storageLogLevel))
                .As<IRocksDbOptionsProvider>()
                .SingleInstance();

            if (!this.usePersistentStorage && this.useBackupAndRestore)
            {
                // Backup and restore serialization
                builder.Register(c => new ProtoBufDataBackupRestore())
                    .As<IDataBackupRestore>()
                    .SingleInstance();
            }

            // IStorageSpaceChecker
            builder.Register(
                c =>
                {
                    IStorageSpaceChecker spaceChecker = !this.usePersistentStorage
                       ? new MemorySpaceChecker(() => 0L) as IStorageSpaceChecker
                       : new NullStorageSpaceChecker();
                    return spaceChecker;
                })
                .As<IStorageSpaceChecker>()
                .SingleInstance();

            // IDbStoreProvider
            builder.Register(
                    async c =>
                    {
                        var loggerFactory = c.Resolve<ILoggerFactory>();
                        ILogger logger = loggerFactory.CreateLogger(typeof(RoutingModule));

                        if (this.usePersistentStorage)
                        {
                            // Create parreplacedions for messages and twins
                            var parreplacedionsList = new List<string> { Core.Constants.MessageStoreParreplacedionKey, Core.Constants.TwinStoreParreplacedionKey, Core.Constants.CheckpointStoreParreplacedionKey };
                            try
                            {
                                IDbStoreProvider dbStoreProvider = DbStoreProvider.Create(
                                    c.Resolve<IRocksDbOptionsProvider>(),
                                    this.storagePath,
                                    parreplacedionsList);
                                logger.LogInformation($"Created persistent store at {this.storagePath}");
                                return dbStoreProvider;
                            }
                            catch (Exception ex) when (!ex.IsFatal())
                            {
                                logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                                IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c);
                                return dbStoreProvider;
                            }
                        }
                        else
                        {
                            logger.LogInformation($"Using in-memory store");
                            IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c);
                            return dbStoreProvider;
                        }
                    })
                .As<Task<IDbStoreProvider>>()
                .SingleInstance();

            // Task<Option<IEncryptionProvider>>
            builder.Register(
                    async c =>
                    {
                        Option<IEncryptionProvider> encryptionProviderOption = await this.workloadUri
                            .Map(
                                async uri =>
                                {
                                    var encryptionProvider = await EncryptionProvider.CreateAsync(
                                        this.storagePath,
                                        new Uri(uri),
                                        this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")),
                                        Constants.WorkloadApiVersion,
                                        this.edgeHubModuleId,
                                        this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                                        Constants.InitializationVectorFileName) as IEncryptionProvider;
                                    return Option.Some(encryptionProvider);
                                })
                            .GetOrElse(() => Task.FromResult(Option.None<IEncryptionProvider>()));
                        return encryptionProviderOption;
                    })
                .As<Task<Option<IEncryptionProvider>>>()
                .SingleInstance();

            // Task<IStoreProvider>
            builder.Register(async c =>
                {
                    var dbStoreProvider = await c.Resolve<Task<IDbStoreProvider>>();
                    IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                    return storeProvider;
                })
                .As<Task<IStoreProvider>>()
                .SingleInstance();

            // Task<IMetadataStore>
            builder.Register(
                    async c =>
                    {
                        var storeProvider = await c.Resolve<Task<IStoreProvider>>();
                        IKeyValueStore<string, string> enreplacedyStore = storeProvider.GetEnreplacedyStore<string, string>("ProductInfo", "MetadataStore");
                        IMetadataStore metadataStore = new MetadataStore(enreplacedyStore, this.productInfo);
                        return metadataStore;
                    })
                .As<Task<IMetadataStore>>()
                .SingleInstance();

            // ITokenProvider
            builder.Register(c => new ClientTokenProvider(c.Resolve<ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1)))
                .Named<ITokenProvider>("EdgeHubClientAuthTokenProvider")
                .SingleInstance();

            // ITokenProvider
            builder.Register(
                    c =>
                    {
                        string deviceId = WebUtility.UrlEncode(this.edgeDeviceId);
                        string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId);
                        return new ClientTokenProvider(c.Resolve<ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1));
                    })
                .Named<ITokenProvider>("EdgeHubServiceAuthTokenProvider")
                .SingleInstance();

            builder.Register(
                    c =>
                    {
                        var loggerFactory = c.Resolve<ILoggerFactory>();
                        var logger = loggerFactory.CreateLogger<RoutingModule>();
                        return Proxy.Parse(this.proxy, logger);
                    })
                .As<Option<IWebProxy>>()
                .SingleInstance();

            // IServiceIdenreplacedyHierarchy
            builder.Register<IServiceIdenreplacedyHierarchy>(
                    c =>
                    {
                        if (this.nestedEdgeEnabled)
                        {
                            return new ServiceIdenreplacedyTree(this.edgeDeviceId);
                        }
                        else
                        {
                            return new ServiceIdenreplacedyDictionary(this.edgeDeviceId);
                        }
                    })
                .As<IServiceIdenreplacedyHierarchy>()
                .SingleInstance();

            // Task<IDeviceScopeIdenreplacediesCache>
            builder.Register(
                    async c =>
                    {
                        IDeviceScopeIdenreplacediesCache deviceScopeIdenreplacediesCache;
                        if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope)
                        {
                            var edgeHubTokenProvider = c.ResolveNamed<ITokenProvider>("EdgeHubServiceAuthTokenProvider");
                            var proxy = c.Resolve<Option<IWebProxy>>();

                            IServiceIdenreplacedyHierarchy serviceIdenreplacedyHierarchy = c.Resolve<IServiceIdenreplacedyHierarchy>();

                            string hostName = this.gatewayHostName.GetOrElse(this.iothubHostName);
                            IDeviceScopeApiClientProvider securityScopesApiClientProvider = new DeviceScopeApiClientProvider(hostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider, serviceIdenreplacedyHierarchy, proxy);
                            IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClientProvider, this.nestedEdgeEnabled);
                            IKeyValueStore<string, string> encryptedStore = await GetEncryptedStore(c, "DeviceScopeCache");
                            deviceScopeIdenreplacediesCache = await DeviceScopeIdenreplacediesCache.Create(serviceIdenreplacedyHierarchy, serviceProxy, encryptedStore, this.scopeCacheRefreshRate, this.scopeCacheRefreshDelay);
                        }
                        else
                        {
                            deviceScopeIdenreplacediesCache = new NullDeviceScopeIdenreplacediesCache();
                        }

                        return deviceScopeIdenreplacediesCache;
                    })
                .As<Task<IDeviceScopeIdenreplacediesCache>>()
                .AutoActivate()
                .SingleInstance();

            // IRegistryApiClient
            builder.Register(
                    c =>
                    {
                        string upstreamHostname = this.gatewayHostName.GetOrElse(this.iothubHostName);
                        var proxy = c.Resolve<Option<IWebProxy>>();
                        var edgeHubTokenProvider = c.ResolveNamed<ITokenProvider>("EdgeHubServiceAuthTokenProvider");
                        return new RegistryOnBehalfOfApiClient(upstreamHostname, proxy, edgeHubTokenProvider);
                    })
                .As<IRegistryOnBehalfOfApiClient>()
                .SingleInstance();

            // Task<ICredentialsCache>
            builder.Register(
                    async c =>
                    {
                        ICredentialsCache underlyingCredentialsCache;
                        if (this.persistTokens)
                        {
                            IKeyValueStore<string, string> encryptedStore = await GetEncryptedStore(c, "CredentialsCache");
                            return new PersistedTokenCredentialsCache(encryptedStore);
                        }
                        else
                        {
                            underlyingCredentialsCache = new NullCredentialsCache();
                        }

                        ICredentialsCache credentialsCache;

                        if (this.nestedEdgeEnabled)
                        {
                            credentialsCache = new NestedCredentialsCache(underlyingCredentialsCache);
                        }
                        else
                        {
                            credentialsCache = new CredentialsCache(underlyingCredentialsCache);
                        }

                        return credentialsCache;
                    })
                .As<Task<ICredentialsCache>>()
                .SingleInstance();

            // Task<IAuthenticator>
            builder.Register(
                    async c =>
                    {
                        IAuthenticator tokenAuthenticator;
                        IAuthenticator certificateAuthenticator;
                        IDeviceScopeIdenreplacediesCache deviceScopeIdenreplacediesCache;
                        var credentialsCacheTask = c.Resolve<Task<ICredentialsCache>>();
                        // by default regardless of how the authenticationMode, X.509 certificate validation will always be scoped
                        deviceScopeIdenreplacediesCache = await c.Resolve<Task<IDeviceScopeIdenreplacediesCache>>();
                        certificateAuthenticator = new DeviceScopeCertificateAuthenticator(deviceScopeIdenreplacediesCache, new NullAuthenticator(), this.trustBundle, true, this.nestedEdgeEnabled);
                        switch (this.authenticationMode)
                        {
                            case AuthenticationMode.Cloud:
                                tokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                                break;

                            case AuthenticationMode.Scope:
                                tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdenreplacediesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), true, true, this.nestedEdgeEnabled);
                                break;

                            default:
                                IAuthenticator cloudTokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                                tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdenreplacediesCache, this.iothubHostName, this.edgeDeviceHostName, cloudTokenAuthenticator, true, true, this.nestedEdgeEnabled);
                                break;
                        }

                        ICredentialsCache credentialsCache = await credentialsCacheTask;
                        return new Authenticator(tokenAuthenticator, certificateAuthenticator, credentialsCache) as IAuthenticator;
                    })
                .As<Task<IAuthenticator>>()
                .SingleInstance();

            // IClientCredentialsFactory
            builder.Register(c => new ClientCredentialsFactory(c.Resolve<IIdenreplacedyProvider>(), this.productInfo))
                .As<IClientCredentialsFactory>()
                .SingleInstance();

            // IClientCredentials "EdgeHubCredentials"
            builder.Register(
                    c =>
                    {
                        var idenreplacedyFactory = c.Resolve<IClientCredentialsFactory>();
                        IClientCredentials edgeHubCredentials = this.edgeHubConnectionString.Map(cs => idenreplacedyFactory.GetWithConnectionString(cs)).GetOrElse(
                            () => idenreplacedyFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeHubModuleId));
                        return edgeHubCredentials;
                    })
                .Named<IClientCredentials>("EdgeHubCredentials")
                .SingleInstance();

            // ServiceIdenreplacedy "EdgeHubIdenreplacedy"
            builder.Register(
                    c =>
                    {
                        return new ServiceIdenreplacedy(
                            this.edgeDeviceId,
                            this.edgeHubModuleId,
                            deviceScope: null,
                            parentScopes: new List<string>(),
                            this.edgeHubGenerationId.GetOrElse("0"),
                            capabilities: new List<string>(),
                            new ServiceAuthentication(ServiceAuthenticationType.None),
                            ServiceIdenreplacedyStatus.Enabled);
                    })
                .Named<ServiceIdenreplacedy>("EdgeHubIdenreplacedy")
                .SingleInstance();

            // ConnectionReauthenticator
            builder.Register(
                    async c =>
                    {
                        var edgeHubCredentials = c.ResolveNamed<IClientCredentials>("EdgeHubCredentials");
                        var connectionManagerTask = c.Resolve<Task<IConnectionManager>>();
                        var authenticatorTask = c.Resolve<Task<IAuthenticator>>();
                        var credentialsCacheTask = c.Resolve<Task<ICredentialsCache>>();
                        var deviceScopeIdenreplacediesCacheTask = c.Resolve<Task<IDeviceScopeIdenreplacediesCache>>();
                        var deviceConnectivityManager = c.Resolve<IDeviceConnectivityManager>();
                        IConnectionManager connectionManager = await connectionManagerTask;
                        IAuthenticator authenticator = await authenticatorTask;
                        ICredentialsCache credentialsCache = await credentialsCacheTask;
                        IDeviceScopeIdenreplacediesCache deviceScopeIdenreplacediesCache = await deviceScopeIdenreplacediesCacheTask;
                        var connectionReauthenticator = new ConnectionReauthenticator(
                            connectionManager,
                            authenticator,
                            credentialsCache,
                            deviceScopeIdenreplacediesCache,
                            TimeSpan.FromMinutes(5),
                            edgeHubCredentials.Idenreplacedy,
                            deviceConnectivityManager);
                        return connectionReauthenticator;
                    })
                .As<Task<ConnectionReauthenticator>>()
                .SingleInstance();

            base.Load(builder);
        }

19 View Source File : DeviceScopeTokenAuthenticatorTest.cs
License : MIT License
Project Creator : Azure

static string GetDeviceToken(string iothubHostName, string deviceId, string key, TimeSpan timeToLive)
        {
            DateTime startTime = DateTime.UtcNow;
            string audience = WebUtility.UrlEncode($"{iothubHostName}/devices/{deviceId}");
            string expiresOn = SasTokenHelper.BuildExpiresOn(startTime, timeToLive);
            string data = string.Join("\n", new List<string> { audience, expiresOn });
            string signature = Sign(data, key);
            return SasTokenHelper.BuildSasToken(audience, signature, expiresOn);
        }

19 View Source File : DeviceScopeTokenAuthenticatorTest.cs
License : MIT License
Project Creator : Azure

static string GetDeviceToken(string iothubHostName, string deviceId, string moduleId, string key)
        {
            DateTime startTime = DateTime.UtcNow;
            string audience = WebUtility.UrlEncode($"{iothubHostName}/devices/{deviceId}/modules/{moduleId}");
            string expiresOn = SasTokenHelper.BuildExpiresOn(startTime, TimeSpan.FromHours(1));
            string data = string.Join("\n", new List<string> { audience, expiresOn });
            string signature = Sign(data, key);
            return SasTokenHelper.BuildSasToken(audience, signature, expiresOn);
        }

19 View Source File : HttpRequestAuthenticatorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_CheckProxyAuthorization_Success()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string moduleId = "module_1";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock<IAuthenticator>();
            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny<IClientCredentials>())).ReturnsAsync(true);

            var clientCertificate = new X509Certificate2(certContentBytes);
            var httpProxiedCertificateExtractor = new Mock<IHttpProxiedCertificateExtractor>();
            httpProxiedCertificateExtractor.Setup(p => p.GetClientCertificate(httpContext)).ReturnsAsync(Option.Some(clientCertificate));

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, idenreplacedyFactory, iothubHostName, httpProxiedCertificateExtractor.Object);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None<string>(), httpContext);
            replacedert.True(result.Authenticated);
            replacedert.Equal(string.Empty, result.ErrorMessage);
        }

19 View Source File : HttpProxiedCertificateExtractorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_NoSasToken_ShouldThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock<IAuthenticator>();

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, idenreplacedyFactory, iothubHostName, deviceId, apiProxyId);
            var ex = await replacedert.ThrowsAsync<AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));
            replacedert.Equal($"Unable to authorize proxy iotedgeApiProxy to forward device certificate - Authorization header missing", ex.Message);
            authenticator.VerifyAll();
        }

19 View Source File : HttpProxiedCertificateExtractorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_InvalidCertificate_ShoudThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = Encoding.UTF8.GetBytes("Invalid cert");
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"{certContentBase64}";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");
            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            var authenticator = new Mock<IAuthenticator>();

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, idenreplacedyFactory, iothubHostName, deviceId, apiProxyId);
            await replacedert.ThrowsAsync<AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));
            authenticator.VerifyAll();
        }

19 View Source File : HttpProxiedCertificateExtractorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_ProxyAuthFailed_ShouldThrow()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");
            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock<IAuthenticator>();
            authenticator.Setup(a => a.AuthenticateAsync(It.Is<IClientCredentials>(c => c.Idenreplacedy.Id == "device_2/iotedgeApiProxy"))).ReturnsAsync(false);

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, idenreplacedyFactory, iothubHostName, deviceId, apiProxyId);
            var ex = await replacedert.ThrowsAsync<AuthenticationException>(() => httpRequestAuthenticator.GetClientCertificate(httpContext));
            replacedert.Equal($"Unable to authorize proxy iotedgeApiProxy to forward device certificate - Unable to authenticate proxy iotedgeApiProxy to forward certificate", ex.Message);
            authenticator.VerifyAll();
        }

19 View Source File : HttpProxiedCertificateExtractorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_ProxyAuthSuccess_ShouldReturnCertificate()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{deviceId}/modules/{apiProxyId}");
            httpContext.Request.Headers.Add(HeaderNames.Authorization, new StringValues(sasToken));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock<IAuthenticator>();
            authenticator.Setup(a => a.AuthenticateAsync(It.Is<IClientCredentials>(c => c.Idenreplacedy.Id == "device_2/iotedgeApiProxy"))).ReturnsAsync(true);

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));

            var httpRequestAuthenticator = new HttpProxiedCertificateExtractor(authenticator.Object, idenreplacedyFactory, iothubHostName, deviceId, apiProxyId);
            var cert = await httpRequestAuthenticator.GetClientCertificate(httpContext);
            replacedert.True(cert.HasValue);
            authenticator.VerifyAll();
        }

19 View Source File : HttpRequestAuthenticatorTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthenticateRequestTestX509ApiProxyForward_NoProxyAuthorization_AuthFailed()
        {
            string iothubHostName = "TestHub.azure-devices.net";
            string deviceId = "device_2";
            string moduleId = "module_1";
            string apiProxyId = "iotedgeApiProxy";
            var httpContext = new DefaultHttpContext();
            httpContext.Connection.RemoteIpAddress = new IPAddress(0);
            var certContentBytes = CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            httpContext.Request.Headers.Add(Constants.ClientCertificateHeaderKey, new StringValues(clientCertString));
            httpContext.Request.QueryString = new QueryString("?api-version=2017-10-20");
            var authenticator = new Mock<IAuthenticator>();
            authenticator.Setup(a => a.AuthenticateAsync(It.IsAny<IClientCredentials>())).ReturnsAsync(true);

            var idenreplacedyFactory = new ClientCredentialsFactory(new IdenreplacedyProvider(iothubHostName));
            var httpProxiedCertificateExtractor = new Mock<IHttpProxiedCertificateExtractor>();
            httpProxiedCertificateExtractor.Setup(p => p.GetClientCertificate(httpContext)).ThrowsAsync(new AuthenticationException($"Unable to authorize proxy {apiProxyId} to forward device certificate - Authorization header missing"));

            var httpRequestAuthenticator = new HttpRequestAuthenticator(authenticator.Object, idenreplacedyFactory, iothubHostName, httpProxiedCertificateExtractor.Object);
            HttpAuthResult result = await httpRequestAuthenticator.AuthenticateAsync(deviceId, Option.Some(moduleId), Option.None<string>(), httpContext);
            replacedert.False(result.Authenticated);
            replacedert.Equal($"Unable to authenticate device with Id device_2/module_1 - Unable to authorize proxy {apiProxyId} to forward device certificate - Authorization header missing", result.ErrorMessage);
        }

19 View Source File : WebSocketHandlingMiddlewareTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task UnauthorizedRequestWhenProxyAuthFails()
        {
            var next = Mock.Of<RequestDelegate>();

            var listener = new Mock<IWebSocketListener>();
            listener.Setup(wsl => wsl.SubProtocol).Returns("abc");
            listener.Setup(
                    wsl => wsl.ProcessWebSocketRequestAsync(
                        It.IsAny<WebSocket>(),
                        It.IsAny<Option<EndPoint>>(),
                        It.IsAny<EndPoint>(),
                        It.IsAny<string>(),
                        It.IsAny<X509Certificate2>(),
                        It.IsAny<IList<X509Certificate2>>(),
                        It.Is<IAuthenticator>(auth => auth != null && auth.GetType() == typeof(NullAuthenticator))))
                .Returns(Task.CompletedTask);

            var registry = new WebSocketListenerRegistry();
            registry.TryRegister(listener.Object);
            var certContentBytes = Util.Test.Common.CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            HttpContext httpContext = this.ContextWithRequestedSubprotocolsAndForwardedCert(new StringValues(clientCertString), "abc");
            var certExtractor = new Mock<IHttpProxiedCertificateExtractor>();
            certExtractor.Setup(p => p.GetClientCertificate(It.IsAny<HttpContext>())).ThrowsAsync(new AuthenticationException());

            var middleware = new WebSocketHandlingMiddleware(next, registry, Task.FromResult(certExtractor.Object));
            await middleware.Invoke(httpContext);

            listener.VerifyAll();
        }

19 View Source File : WebSocketHandlingMiddlewareTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task AuthorizedRequestWhenProxyAuthSuccess()
        {
            var next = Mock.Of<RequestDelegate>();

            var listener = new Mock<IWebSocketListener>();
            listener.Setup(wsl => wsl.SubProtocol).Returns("abc");
            listener.Setup(
                    wsl => wsl.ProcessWebSocketRequestAsync(
                        It.IsAny<WebSocket>(),
                        It.IsAny<Option<EndPoint>>(),
                        It.IsAny<EndPoint>(),
                        It.IsAny<string>(),
                        It.IsAny<X509Certificate2>(),
                        It.IsAny<IList<X509Certificate2>>(),
                        It.Is<IAuthenticator>(auth => auth == null)))
                .Returns(Task.CompletedTask);

            var registry = new WebSocketListenerRegistry();
            registry.TryRegister(listener.Object);
            var certContentBytes = Util.Test.Common.CertificateHelper.GenerateSelfSignedCert($"test_cert").Export(X509ContentType.Cert);
            string certContentBase64 = Convert.ToBase64String(certContentBytes);
            string clientCertString = $"-----BEGIN CERTIFICATE-----\n{certContentBase64}\n-----END CERTIFICATE-----\n";
            clientCertString = WebUtility.UrlEncode(clientCertString);
            HttpContext httpContext = this.ContextWithRequestedSubprotocolsAndForwardedCert(new StringValues(clientCertString), "abc");
            var certExtractor = new Mock<IHttpProxiedCertificateExtractor>();
            certExtractor.Setup(p => p.GetClientCertificate(It.IsAny<HttpContext>())).ReturnsAsync(Option.Some(new X509Certificate2(certContentBytes)));

            var middleware = new WebSocketHandlingMiddleware(next, registry, Task.FromResult(certExtractor.Object));
            await middleware.Invoke(httpContext);

            listener.VerifyAll();
        }

19 View Source File : SharedAccessSignatureTest.cs
License : MIT License
Project Creator : Azure

private string GetNonExpiredToken()
        {
            // Generate a valid looking sas token
            var expiry = this.GetExpiry(10).ToString();
            var sr = "test";

            var sig = SharedAccessSignature.ComputeSignature(Convert.FromBase64String("test"), sr, expiry);
            sig = WebUtility.UrlEncode(sig);

            return "SharedAccessSignature\nsig=" + sig + "&se=" + expiry + "&sr=" + sr;
        }

19 View Source File : SasTokenHelper.cs
License : MIT License
Project Creator : Azure

public static string BuildSasToken(string audience, string signature, string expiry)
        {
            // Example returned string:
            // SharedAccessSignature sr=ENCODED(dh://myiothub.azure-devices.net/a/b/c?myvalue1=a)&sig=<Signature>&se=<ExpiresOnValue>[&skn=<KeyName>]
            var buffer = new StringBuilder();
            buffer.AppendFormat(
                CultureInfo.InvariantCulture,
                "{0} {1}={2}&{3}={4}&{5}={6}",
                SharedAccessSignature,
                AudienceFieldName,
                audience,
                SignatureFieldName,
                WebUtility.UrlEncode(signature),
                ExpiryFieldName,
                WebUtility.UrlEncode(expiry));

            return buffer.ToString();
        }

19 View Source File : SasTokenHelper.cs
License : MIT License
Project Creator : Azure

public static string BuildAudience(string iotHub, string deviceId, string moduleId) =>
            WebUtility.UrlEncode(Invariant($"{iotHub}/devices/{WebUtility.UrlEncode(deviceId)}/modules/{WebUtility.UrlEncode(moduleId)}"));

19 View Source File : SasTokenHelper.cs
License : MIT License
Project Creator : Azure

public static string BuildAudience(string iotHub, string deviceId) =>
            WebUtility.UrlEncode(Invariant($"{iotHub}/devices/{WebUtility.UrlEncode(deviceId)}"));

19 View Source File : Program.cs
License : MIT License
Project Creator : Azure-Samples

private static string GenerateSasToken(string resourceUri, string sharedAccessKey, string policyName, DateTime expiresOn)
        {
            DateTime epochTime = new DateTime(1970, 1, 1);
            TimeSpan secondsFromEpochTime = expiresOn.Subtract(epochTime);
            long seconds = Convert.ToInt64(secondsFromEpochTime.TotalSeconds, CultureInfo.InvariantCulture);
            string expiry = Convert.ToString(seconds, CultureInfo.InvariantCulture);

            string stringToSign = WebUtility.UrlEncode(resourceUri) + "\n" + expiry;

            HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(sharedAccessKey));
            string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

            // SharedAccessSignature sr=ENCODED(dh://myiothub.azure-devices.net/a/b/c?myvalue1=a)&sig=<Signature>&se=<ExpiresOnValue>[&skn=<KeyName>]
            string token = string.Format(
                CultureInfo.InvariantCulture,
                "SharedAccessSignature sr={0}&sig={1}&se={2}",
                WebUtility.UrlEncode(resourceUri),
                WebUtility.UrlEncode(signature),
                expiry);

            if (!string.IsNullOrWhiteSpace(policyName))
            {
                token += "&skn=" + policyName;
            }

            return token;
        }

19 View Source File : IotHubConnection.cs
License : MIT License
Project Creator : Azure-Samples

private static string BuildSignature(
            string resourceUri,
            string keyName,
            string keyValue,
            TimeSpan validityDuration)
        {
            using var hmac = new HMACSHA256(Convert.FromBase64String(keyValue));

            var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var expirationTime = Convert.ToInt64((DateTimeOffset.UtcNow.Add(validityDuration) - epoch).TotalSeconds);
            var encodedAudience = WebUtility.UrlEncode(resourceUri);
            var expiration = Convert.ToString(expirationTime, CultureInfo.InvariantCulture);
            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{ encodedAudience }\n{ expiration }")));

            return string.Format(
                CultureInfo.InvariantCulture,
                "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                encodedAudience,
                WebUtility.UrlEncode(signature),
                WebUtility.UrlEncode(expiration),
                WebUtility.UrlEncode(keyName));
        }

19 View Source File : PactVerifier.cs
License : MIT License
Project Creator : bartschotten

internal static async Task PublishTags(HttpClient pactBrokerClient, string providerName, string providerVersion, IList<string> tags)
        {
            foreach (var tag in tags)
            {
                var content = new StringContent("", Encoding.UTF8, "application/json");
                var response = await pactBrokerClient.PutAsync($"pacticipants/{WebUtility.UrlEncode(providerName)}/versions/{WebUtility.UrlEncode(providerVersion)}/tags/{WebUtility.UrlEncode(tag)}", content);
                if (!response.IsSuccessStatusCode)
                {
                    throw new PactException($"Publishing tag '{tag}' failed. Pact Broker returned " + response.StatusCode);
                }
            }
        }

19 View Source File : GeocoderService.cs
License : Apache License 2.0
Project Creator : bcgov

public async Task<FeatureCollectionModel> GetSiteAddressesAsync(string address, string outputFormat = "json")
        {
            var parameters = new AddressesParameters()
            {
                AddressString = WebUtility.UrlEncode(address)
            };
            return await GetSiteAddressesAsync(parameters, outputFormat);
        }

19 View Source File : IBodyFormater.cs
License : Apache License 2.0
Project Creator : beetlex-io

public override void Serialization(Request request, object data, PipeStream stream)
        {
            if (data != null)
            {
                System.Collections.IDictionary keyValuePairs = data as IDictionary;
                if (keyValuePairs != null)
                {
                    int i = 0;
                    foreach (object key in keyValuePairs.Keys)
                    {
                        object value = keyValuePairs[key];
                        if (value != null)
                        {
                            if (i > 0)
                                stream.Write("&");
                            stream.Write(key.ToString() + "=");
                            if (value is string)
                            {
                                stream.Write(System.Net.WebUtility.UrlEncode((string)value));
                            }
                            else
                            {
                                if (value is IEnumerable subitems)
                                {
                                    List<string> values = new List<string>();
                                    foreach (var v in subitems)
                                        values.Add(v.ToString());
                                    stream.Write(string.Join(",", values));
                                }
                                else
                                {
                                    stream.Write(System.Net.WebUtility.UrlEncode(value.ToString()));
                                }
                            }
                            i++;
                        }
                    }
                }
                else
                {
                    stream.Write(data.ToString());
                }
            }
        }

19 View Source File : Request.cs
License : Apache License 2.0
Project Creator : beetlex-io

internal void Execute(PipeStream stream)
        {
            try
            {
                var buffer = HttpParse.GetByteBuffer();
                int offset = 0;
                offset += Encoding.ASCII.GetBytes(Method, 0, Method.Length, buffer, offset);
                buffer[offset] = HeaderTypeFactory._SPACE_BYTE;
                offset++;
                offset += Encoding.ASCII.GetBytes(Url, 0, Url.Length, buffer, offset);
                if (QuestryString != null && QuestryString.Count > 0)
                {
                    int i = 0;
                    foreach (var item in this.QuestryString)
                    {
                        string key = item.Key;
                        string value = item.Value;
                        if (string.IsNullOrEmpty(value))
                            continue;
                        value = System.Net.WebUtility.UrlEncode(value);
                        if (i == 0)
                        {
                            buffer[offset] = HeaderTypeFactory._QMARK;
                            offset++;
                        }
                        else
                        {
                            buffer[offset] = HeaderTypeFactory._AND;
                            offset++;
                        }
                        offset += Encoding.ASCII.GetBytes(key, 0, key.Length, buffer, offset);
                        buffer[offset] = HeaderTypeFactory._EQ;
                        offset++;
                        offset += Encoding.ASCII.GetBytes(value, 0, value.Length, buffer, offset);
                        i++;
                    }
                }
                buffer[offset] = HeaderTypeFactory._SPACE_BYTE;
                offset++;
                offset += Encoding.ASCII.GetBytes(HttpProtocol, 0, HttpProtocol.Length, buffer, offset);
                buffer[offset] = HeaderTypeFactory._LINE_R;
                offset++;
                buffer[offset] = HeaderTypeFactory._LINE_N;
                offset++;
                stream.Write(buffer, 0, offset);

                Formater?.Setting(this);
                if (Header != null)
                    Header.Write(stream);

                if (Method == POST || Method == PUT)
                {
                    if (Body != null)
                    {
                        stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, 16);
                        MemoryBlockCollection contentLength = stream.Allocate(10);
                        stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                        int len = stream.CacheLength;
                        Formater.Serialization(this, Body, stream);
                        int count = stream.CacheLength - len;
                        contentLength.Full(count.ToString().PadRight(10), stream.Encoding);
                    }
                    else
                    {
                        stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                        stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    }
                }
                else
                {
                    stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                }
            }
            catch (Exception e)
            {
                Client?.DisConnect();
                throw new HttpClientException($"http client write data error {e.Message}", e);
            }
        }

19 View Source File : GitterMessageOptions.cs
License : MIT License
Project Creator : Blazored

public override string ToString()
        {
            StringBuilder s = new StringBuilder("?");
            
            if (!string.IsNullOrWhiteSpace(AfterId))
            {
                s.Append($"afterId={AfterId.Trim()}");
            }
            if (!string.IsNullOrWhiteSpace(BeforeId))
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"beforeId={BeforeId.Trim()}");
            }
            if (!string.IsNullOrWhiteSpace(Lang))
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"lang={Lang.Trim()}");
            }
            if (!string.IsNullOrWhiteSpace(Query))
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"q={System.Net.WebUtility.UrlEncode(Query.Trim())}");
            }
            if (Limit > 0)
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"limit={Limit}");
            }
            if (Skip > 0)
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"skip={Skip}");
            }

            if (s.Length == 1) s.Clear();
            return s.ToString();
        }

19 View Source File : GitterRoomUserOptions.cs
License : MIT License
Project Creator : Blazored

public override string ToString()
        {
            StringBuilder s = new StringBuilder("?");

            if (!string.IsNullOrWhiteSpace(Query))
            {
                s.Append($"q={System.Net.WebUtility.UrlEncode(Query.Trim())}");
            }
            if (Limit > 0)
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"limit={Limit}");
            }
            if (Skip > 0)
            {
                if (s.Length > 1) s.Append("&");
                s.Append($"skip={Skip}");
            }

            if (s.Length == 1) s.Clear();
            return s.ToString();
        }

19 View Source File : RESTGeocode.cs
License : MIT License
Project Creator : blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure<GH_String> Addresses = new GH_Structure<GH_String>();

            DA.GetDataTree<GH_String>("Addresses", out Addresses);

            GH_Structure<GH_String> addr = new GH_Structure<GH_String>();
            GH_Structure<GH_String> latx = new GH_Structure<GH_String>();
            GH_Structure<GH_String> lony = new GH_Structure<GH_String>();

            for (int a = 0; a < Addresses.Branches.Count; a++)
            {
                IList branch = Addresses.Branches[a];
                GH_Path path = Addresses.Paths[a];
                int count = 0;
                foreach (GH_String addressString in branch)
                {
                    string address = System.Net.WebUtility.UrlEncode(addressString.Value);
                    string output = GetData("https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?Address=" + address + "&f=pjson");
                    JObject ja = JObject.Parse(output);

                    if (ja["candidates"].Count() < 1)
                    {
                        addr.Append(new GH_String("No Cadidate location found for this address"), path);
                        lony.Append(new GH_String(""), path);
                        latx.Append(new GH_String(""), path);
                    }
                    else
                    {
                        for (int i = 0; i < ja["candidates"].Count(); i++)
                        {
                            if (ja["candidates"][i]["score"].Value<int>() > 99)
                            {
                                addr.Append(new GH_String(ja["candidates"][i]["address"].ToString()), new GH_Path(path[count], i));
                                addr.Append(new GH_String("LON: " + ja["candidates"][i]["location"]["x"].ToString()), new GH_Path(path[count], i));
                                addr.Append(new GH_String("LAT: " + ja["candidates"][i]["location"]["y"].ToString()), new GH_Path(path[count], i));
                                lony.Append(new GH_String(ja["candidates"][i]["location"]["y"].ToString()), new GH_Path(path[count], i));
                                latx.Append(new GH_String(ja["candidates"][i]["location"]["x"].ToString()), new GH_Path(path[count], i));
                            }
                        }
                    }
                }
            }

            if (addr == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No Candidate locations found");
                return;
            }
            else
            {
                DA.SetDataTree(0, addr);
                DA.SetDataTree(1, lony);
                DA.SetDataTree(2, latx);
            }


        }

19 View Source File : RESTTOSM.cs
License : MIT License
Project Creator : blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;
            DA.GetData<Curve>(0, ref boundary);

            string folderPath = string.Empty;
            DA.GetData<string>(1, ref folderPath);
            if (!folderPath.EndsWith(@"\")) folderPath = folderPath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(2, ref prefix);
            if (prefix == "")
            {
                prefix = osmSource;
            }

            string searchTerm = string.Empty;
            DA.GetData<string>(3, ref searchTerm);
            if (!String.IsNullOrEmpty(searchTerm))
            {
                searchTerm = System.Net.WebUtility.UrlEncode("[" + searchTerm + "]");
            }

            string overpreplacedQL = string.Empty;
            DA.GetData<string>(4, ref overpreplacedQL);

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            /// hardcoded timout integer
            /// TODO: add this as a menu item that can be customized
            int timeout = 60;

            string URL = osmURL;

            GH_Structure<GH_String> osmList = new GH_Structure<GH_String>();
            GH_Structure<GH_String> osmQuery = new GH_Structure<GH_String>();

            string oQ = string.Empty;

            string left = string.Empty;
            string bottom = string.Empty;
            string right = string.Empty;
            string top = string.Empty;

            ///Construct query with bounding box
            if (boundary != null)
            {
                /// Check boundary to make sure it's valid
                if (!boundary.GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }

                //offset boundary to ensure data from opentopography fully contains query boundary
                //double offsetD = 200 * Rhino.RhinoMath.UnitScale(UnitSystem.Meters, Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem);
                //Curve offsetB = boundary.Offset(Plane.WorldXY, offsetD, 1, CurveOffsetCornerStyle.Sharp)[0];
                //offsetB = boundary;

                //Get OSM frame for given boundary
                Point3d min = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Min);
                Point3d max = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Max);

                left = min.X.ToString();
                bottom = min.Y.ToString();
                right = max.X.ToString();
                top = max.Y.ToString();

                ///Override search with Query Language
                if (!String.IsNullOrEmpty(overpreplacedQL))
                {
                    string bbox = "(" + bottom + "," + left + "," + top + "," + right + ")";
                    overpreplacedQL = overpreplacedQL.Replace("{bbox}", bbox);
                    oQ = osmURL.Split('=')[0] + "=" + overpreplacedQL;
                    osmQuery.Append(new GH_String(oQ));
                    DA.SetDataTree(1, osmQuery);
                }

                else
                {
                    oQ = Convert.GetOSMURL(timeout, searchTerm, left, bottom, right, top, osmURL);
                    osmQuery.Append(new GH_String(oQ));
                    DA.SetDataTree(1, osmQuery);
                }
            }

            ///Construct query with Overpreplaced QL 
            ///https://wiki.openstreetmap.org/wiki/Overpreplaced_API/Language_Guide
            else if (!String.IsNullOrEmpty(overpreplacedQL) && boundary == null)
            {
                oQ = osmURL.Split('=')[0] + "=" + overpreplacedQL;
                osmQuery.Append(new GH_String(oQ));
                DA.SetDataTree(1, osmQuery);
            }


            if (run)
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadFile(oQ, folderPath + prefix + ".osm");
                webClient.Dispose();
            }

            osmList.Append(new GH_String(folderPath + prefix + ".osm"));



            //populate outputs
            DA.SetDataTree(0, osmList);

        }

19 View Source File : AzureAdAuthMiddleware.cs
License : MIT License
Project Creator : BotBuilderCommunity

public async Task OnTurnAsync(ITurnContext context, NextDelegate next, CancellationToken cancellationToken = default(CancellationToken))
        {
            var authToken = TokenStorage.LoadConfiguration(context.Activity.Conversation.Id);

            if (authToken == null)
            {
                if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation())
                {
                    var conversationReference = context.Activity.GetConversationReference();

                    var serializedCookie = WebUtility.UrlEncode(JsonConvert.SerializeObject(conversationReference));

                    var signInUrl = AzureAdExtensions.GetUserConsentLoginUrl(AzureAdTenant, AppClientId, AppRedirectUri, PermissionsRequested, serializedCookie);

                    var activity = context.Activity.CreateReply();
                    activity.AddSignInCard(signInUrl);

                    await context.SendActivityAsync(activity);
                }
            }
            else if (authToken.ExpiresIn < DateTime.Now.AddMinutes(-10))
            {
                if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation())
                {
                    var client = new HttpClient();
                    var accessToken = await AzureAdExtensions.GetAccessTokenUsingRefreshToken(client, AzureAdTenant, authToken.RefreshToken, AppClientId, AppRedirectUri, AppClientSecret, PermissionsRequested);

                    // have to save it
                    authToken = new ConversationAuthToken(context.Activity.Conversation.Id)
                    {
                        AccessToken = accessToken.accessToken,
                        RefreshToken = accessToken.refreshToken,
                        ExpiresIn = accessToken.refreshTokenExpiresIn
                    };
                    TokenStorage.SaveConfiguration(authToken);

                    // make the authtoken available to downstream pipeline components
                    context.TurnState.Add(AUTH_TOKEN_KEY, authToken);
                    await next(cancellationToken);
                }
            }
            else
            {
                // make the authtoken available to downstream pipeline components
                context.TurnState.Add(AUTH_TOKEN_KEY, authToken);
                await next(cancellationToken);
            }
        }

19 View Source File : PoeDBHelper.cs
License : MIT License
Project Creator : C1rdec

public static Uri CreateItemUri(string name)
        {
            // replace space encodes with '_' to match the link layout of the poe wiki and then url encode it
            name = name.Replace("'", string.Empty).Trim();
            var itemLink = System.Net.WebUtility.UrlEncode(name.Replace(" ", "_"));

            return new Uri(BaseUri + itemLink);
        }

19 View Source File : PoeDBHelper.cs
License : MIT License
Project Creator : C1rdec

public static Uri GereplacedemImageUrl(string name)
        {
            var webPage = new HtmlWeb();
            name = name.Replace("'", string.Empty).Trim();
            var escapeName = System.Net.WebUtility.UrlEncode(name.Replace(" ", "_"));

            return ParseMedia($"{BaseUri}{escapeName}", webPage);
        }

19 View Source File : WikiHelper.cs
License : MIT License
Project Creator : C1rdec

public static Uri CreateItemUri(string name)
        {
            // replace space encodes with '_' to match the link layout of the poe wiki and then url encode it
            var itemLink = System.Net.WebUtility.UrlEncode(name.Replace(" ", "_"));
            return new Uri(WikiBaseUri + itemLink);
        }

19 View Source File : WikiHelper.cs
License : MIT License
Project Creator : C1rdec

public static Uri GereplacedemImageUrl(string name)
        {
            var webPage = new HtmlWeb();
            var escapeName = System.Net.WebUtility.UrlEncode(name.Replace(" ", "_"));

            return ParseMedia($"{WikiBaseUri}{escapeName}", webPage);
        }

19 View Source File : WebUtilityExtended.cs
License : MIT License
Project Creator : CalciumFramework

public static string UrlEncode(string text)
			=> WebUtility.UrlEncode(text);

19 View Source File : CustomFormUrlEncodedContent.cs
License : MIT License
Project Creator : cctrbic

private static string Encode(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return string.Empty;
            }
            return System.Net.WebUtility.UrlEncode(data).Replace("%20", "+");
        }

19 View Source File : NotAuthorizedHandlerTests.cs
License : MIT License
Project Creator : christiansparre

[Fact]
        public void ShouldRedirectToSignInPageIfNotAuthenticated()
        {
            _authenticationStateProvider.Setup(s => s.GetAuthenticationStateAsync()).ReturnsAsync(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdenreplacedy())));

            var component = testHost.AddComponent<NotAuthorizedHandler>();

            var navigation = _testNavigationManager.Navigations.Pop();
            navigation.uri.ShouldBe($"/account/signin?returnUrl={WebUtility.UrlEncode("/test/test")}");
            navigation.forceLoad.ShouldBeFalse();
        }

19 View Source File : NotAuthorizedHandlerTests.cs
License : MIT License
Project Creator : christiansparre

[Fact]
        public void ShouldIncludeReturnUrlInRedirectToSignInPageIfNotAuthenticated()
        {
            _authenticationStateProvider.Setup(s => s.GetAuthenticationStateAsync()).ReturnsAsync(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdenreplacedy())));

            var component = testHost.AddComponent<NotAuthorizedHandler>();

            var nav = _testNavigationManager.Navigations.Pop();
            nav.uri.ShouldEndWith($"?returnUrl={WebUtility.UrlEncode("/test/test")}");
        }

19 View Source File : RequestPayloadBuilder.cs
License : GNU Lesser General Public License v3.0
Project Creator : cnAbp

private static string GenerateFormPostData(ActionApiDescriptionModel action, IReadOnlyDictionary<string, object> methodArguments)
        {
            var parameters = action
                .Parameters
                .Where(p => p.BindingSourceId == ParameterBindingSources.Form)
                .ToArray();

            if (!parameters.Any())
            {
                return null;
            }

            var postDataBuilder = new StringBuilder();

            var isFirstParam = true;
            foreach (var queryStringParameter in parameters)
            {
                var value = HttpActionParameterHelper.FindParameterValue(methodArguments, queryStringParameter);
                if (value == null)
                {
                    continue;
                }

                postDataBuilder.Append(isFirstParam ? "?" : "&");
                postDataBuilder.Append(queryStringParameter.Name + "=" + System.Net.WebUtility.UrlEncode(value.ToString()));

                isFirstParam = false;
            }

            return postDataBuilder.ToString();
        }

19 View Source File : UrlBuilder.cs
License : GNU Lesser General Public License v3.0
Project Creator : cnAbp

private static void AddQueryStringParameter(StringBuilder urlBuilder, bool isFirstParam, string name, object value)
        {
            urlBuilder.Append(isFirstParam ? "?" : "&");
            urlBuilder.Append(name + "=" + System.Net.WebUtility.UrlEncode(value.ToString()));
        }

19 View Source File : GravatarTagHelper.cs
License : GNU Lesser General Public License v3.0
Project Creator : cnAbp

private string GetDefaultImageParameter()
        {
            return "&d=" + (!string.IsNullOrEmpty(DefaultImageUrl)
                       ? System.Net.WebUtility.UrlEncode(DefaultImageUrl)
                       : GetEnumDescription(DefaultImage));
        }

19 View Source File : New.cshtml.cs
License : GNU Lesser General Public License v3.0
Project Creator : cnAbp

public async Task<ActionResult> OnPost()
        {
            var blog = await _blogAppService.GetAsync(Post.BlogId);
            var postWithDetailsDto = await _postAppService.CreateAsync(ObjectMapper.Map<CreatePostViewModel,CreatePostDto>(Post));

            //TODO: Try Url.Page(...)
            return Redirect(Url.Content($"~/blog/{WebUtility.UrlEncode(blog.ShortName)}/{WebUtility.UrlEncode(postWithDetailsDto.Url)}"));
        }

19 View Source File : UrlUtil.cs
License : MIT License
Project Creator : cocosip

public static string UrlAttachParameters(string url, Dictionary<string, string> paramDict,
            bool replaceSame = false)
        {
            var parameters = GetUrlParameters(url);
            var sortParameters = new SortedDictionary<string, string>(parameters);
            foreach (var kv in paramDict)
            {
                if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value))
                {
                    if (sortParameters.ContainsKey(kv.Key.ToLower()))
                    {
                        if (replaceSame)
                        {
                            sortParameters[kv.Key.ToLower()] = kv.Value;
                        }
                    }
                    else
                    {
                        sortParameters.Add(kv.Key, kv.Value);
                    }
                }
            }
            var uri = new Uri(url);
            var separator = sortParameters.Any() ? "?" : "";
            var parameterUri = string.Join("&", sortParameters.Select(x => string.Concat(x.Key, "=", WebUtility.UrlEncode(x.Value))));
            UriBuilder uriBuilder = new UriBuilder()
            {
                Host = uri.Host,
                Scheme = uri.Scheme,
                Fragment = uri.Fragment,
                Path = uri.LocalPath,
                Query = string.Concat(separator, parameterUri),
            };

            return uriBuilder.Uri.ToString();
        }

19 View Source File : Query.cs
License : MIT License
Project Creator : codecov

private void SetSlug()
        {
            QueryParameters["slug"] = string.Empty;

            foreach (var repository in Repositories)
            {
                if (!string.IsNullOrWhiteSpace(repository.Slug))
                {
                    QueryParameters["slug"] = WebUtility.UrlEncode(repository.Slug);
                    break;
                }
            }

            var slugEnv = _environmentVariables.GetEnvironmentVariable("CODECOV_SLUG");
            if (!string.IsNullOrWhiteSpace(slugEnv))
            {
                QueryParameters["slug"] = WebUtility.UrlEncode(slugEnv.Trim());
            }

            if (!string.IsNullOrWhiteSpace(Options.Slug))
            {
                QueryParameters["slug"] = WebUtility.UrlEncode(Options.Slug.Trim());
            }
        }

See More Examples