public static async ValueTask <Resource> GetResource(this IFactoryContext factoryContext, Uri uri, NameValueCollection?headers, CancellationToken token) { if (factoryContext is null) { throw new ArgumentNullException(nameof(factoryContext)); } var factories = factoryContext.ResourceLoaderFactories; if (!factories.IsDefaultOrEmpty) { foreach (var resourceLoaderFactory in factories) { if (await resourceLoaderFactory.TryGetActivator(factoryContext, uri, token).ConfigureAwait(false) is { } activator) { var resourceLoader = await activator.CreateResourceLoader(factoryContext, token).ConfigureAwait(false); return(await resourceLoader.Request(uri, headers, token).ConfigureAwait(false)); } } } throw new ProcessorException(Resources.Exception_CannotFindResourceLoaderToLoadExternalResource); }
public override void WriteJson(JsonWriter writer, NameValueCollection?collection, JsonSerializer serializer, IReadOnlyDictionary <string, object> context) { if (collection is null) { return; } Dictionary <string, string?> dictionary = new(); foreach (string?key in collection) { var value = collection.Get(key); string?notNullKey; if (key == null) { notNullKey = "null"; } else { if (ignoredByNameMembers.Contains(key)) { continue; } notNullKey = key; } value ??= "null"; dictionary[notNullKey] = value; } serializer.Serialize(writer, dictionary); }
/// <summary>将名值集合转换成字符串,key1=value1&key2=value2,k/v会编码</summary> /// <param name="source">数据源</param> /// <returns>字符串</returns> public static string ToQueryString(this NameValueCollection?source) { if (source == null || source.Count <= 0) { return(string.Empty); } var sb = new StringBuilder(1024); foreach (var key in source.AllKeys) { if (string.IsNullOrWhiteSpace(key)) { continue; } sb.Append("&"); sb.Append(key.UrlEncode()); sb.Append("="); var val = source.Get(key); if (val != null) { sb.Append(val.UrlEncode()); } } return(sb.Length > 0 ? sb.ToString(1, sb.Length - 1) : ""); }
private void ProcessRequest(ref ArraySegment <byte> data) { var requestBuffer = data.Array !; var requestBody = (ReadOnlySpan <byte>)data; var ret = RequestReader.Parse(ref requestBody, BaseUri) !; HttpRequest = ret.Item1; ContentHeaders = ret.Item2; Options.RequestProcessor !.Process(this, HttpRequest); var pooledBuffer = Tunnel.ArrayPool.Rent(data.Count + 8096); // write request back int requestLength; using (var memoryStream = new MemoryStream(pooledBuffer)) { using (var streamWriter = new StreamWriter(memoryStream, leaveOpen: true)) { RequestWriter.WriteRequest(streamWriter, HttpRequest, requestBody.Length, ContentHeaders); } requestLength = (int)memoryStream.Position; } requestBody.CopyTo(pooledBuffer.AsSpan(requestLength)); data = new(pooledBuffer, 0, requestLength + requestBody.Length); // return current buffer Tunnel.ArrayPool.Return(requestBuffer); }
/// <summary> /// Initializes the <see cref="Configuration"/> class. /// </summary> static Configuration() { try { configuration = (NameValueCollection)ConfigurationManager.GetSection("quartz"); } catch (Exception e) { log.Warn("could not read configuration using ConfigurationManager.GetSection: " + e.Message); } }
public static AppRunner GetAppRunner(NameValueCollection?appSettings = null) { appSettings ??= new NameValueCollection(); return(new AppRunner <Examples>() .UseDefaultMiddleware() .UseLog2ConsoleDirective() .UseNameCasing(Case.KebabCase) .UseFluentValidation() .UseInteractiveMode("Example") .UseDefaultsFromAppSetting(appSettings, includeNamingConventions: true)); }
public static AppRunner GetAppRunner(NameValueCollection?appConfigSettings = null, string?appNameForTests = "example_app") { appConfigSettings ??= new NameValueCollection(); return(new AppRunner <Examples>(appNameForTests is null ? null : new AppSettings { Help = { UsageAppName = appNameForTests } }) .UseDefaultMiddleware() .UseLog2ConsoleDirective() .UseNameCasing(Case.KebabCase) .UseFluentValidation() .UseInteractiveMode("Example") .UseDefaultsFromAppSetting(appConfigSettings, includeNamingConventions: true)); }
private string BuildRequestCacheKey(string uri, NameValueCollection?parameters) { if (parameters is null) { return($"req-{uri}"); } var combinedParameters = parameters.Keys .Cast <string>() .Select(s => s + ":" + parameters[s]); return($"req-{uri}-{{{string.Join(";", combinedParameters)}}}"); }
/// <summary> /// A NameValueCollection extension method that converts the @this to a dictionary. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as an IDictionary<string,object></returns> public static IDictionary <string, string?> ToDictionary(this NameValueCollection? @this) { var dict = new Dictionary <string, string?>(); if (@this != null) { foreach (var key in @this.AllKeys) { dict.Add(Guard.NotNull(key), @this[key]); } } return(dict); }
internal static int CreateAndRunServer( string pipeName, ICompilerServerHost?compilerServerHost = null, IClientConnectionHost?clientConnectionHost = null, IDiagnosticListener?listener = null, TimeSpan?keepAlive = null, NameValueCollection?appSettings = null, CancellationToken cancellationToken = default) { appSettings ??= new NameValueCollection(); var controller = new BuildServerController(appSettings); return(controller.RunServer(pipeName, compilerServerHost, clientConnectionHost, listener, keepAlive, cancellationToken)); }
public async Task <IActionResult> OnGet() { NameValueCollection?query = null; if (!string.IsNullOrWhiteSpace(QueryString)) { query = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(QueryString).ToLowerInvariant()); } if (ForumId == null && query != null) { ForumId = int.TryParse(query["forumid"], out var i) ? i as int? : null; } if (TopicId == null && query != null) { TopicId = int.TryParse(query["topicid"], out var i) ? i as int? : null; } var connection = Context.GetDbConnection(); Users = await UserService.GetUserMap(); if (ForumId == null && TopicId != null) { ForumId = (await connection.QueryFirstOrDefaultAsync <PhpbbTopics>("SELECT * FROM phpbb_topics WHERE topic_id = @topicId", new { TopicId }))?.ForumId; } if (ForumId == null && TopicId == null && query != null) { var postId = int.TryParse(query["postid"], out var i) ? i as int? : null; var post = await connection.QueryFirstOrDefaultAsync <PhpbbPosts>("SELECT * FROM phpbb_posts WHERE post_id = @postId", new { postId }); TopicId = post?.TopicId; ForumId = post?.ForumId; } if (DoSearch ?? false) { PageNum = Paginator.NormalizePageNumberLowerBound(PageNum); await Utils.RetryOnceAsync( toDo : () => Search(), evaluateSuccess : () => (Posts?.Count ?? 0) > 0 && PageNum == Paginator?.CurrentPage, fix : () => PageNum = Paginator.NormalizePageNumberLowerBound(Paginator?.CurrentPage)); } return(Page()); }
public static string BuildUrl(this NameValueCollection? @params, string url) { @params ??= new NameValueCollection(); if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(nameof(url)); } foreach (var c in Enumerable.Range(0, @params.Count)) { url = QueryHelpers.AddQueryString(url, @params.GetKey(c), @params.Get(c)); } return(url); }
public static IEnumerable <KeyValuePair <string, string?> > ToKeyValuePair(this NameValueCollection?collection) { if (collection == null || collection.Count == 0) { yield break; } foreach (var key in collection.AllKeys) { if (string.IsNullOrWhiteSpace(key)) { continue; } yield return(new KeyValuePair <string, string?>(key, collection[key])); } }
public static string Build(string baseUrl, string?additionalPath = null, NameValueCollection?queryParams = null) { if (additionalPath != null) { baseUrl = $"{baseUrl.TrimEnd('/')}/{additionalPath}"; } if (queryParams != null) { var builder = new UriBuilder(baseUrl) { Query = ToQueryString(queryParams) }; // Remove port number baseUrl = builder.Uri .GetComponents(UriComponents.AbsoluteUri & ~UriComponents.StrongPort, UriFormat.UriEscaped); } return(baseUrl); }
/// <summary> /// 格式化异常信息 /// </summary> /// <param name="exception"></param> /// <param name="collection"></param> /// <returns></returns> public static string Format(this Exception exception, NameValueCollection?collection = null) { var logger = new StringBuilder(); if (collection != null) { foreach (string key in collection) { logger.AppendFormat("{0}: {1}", key, collection[key]); logger.AppendLine(); } } logger.AppendFormat("{0}: {1}", nameof(Exception.Message), exception.Message); logger.AppendLine(); logger.AppendLine(new string('*', 45)); logger.AppendFormat("{0}: {1}", nameof(Exception.StackTrace), exception.StackTrace); logger.AppendLine(); return(logger.ToString()); }
protected virtual async Task <T> PostAsync <T>(string url, object?content, NameValueCollection? @params = null) { try { var uri = @params.BuildUrl(url); var stringContent = new StringContent( _jsonSerializer.Serialize(content), Encoding.UTF8, MediaTypeNames.Application.Json ); var response = await _httpClient.PostAsync(uri, stringContent).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return(_jsonSerializer.Deserialize <T>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); } catch (Exception e) { Logger.LogError(e, e.Message); ExceptionDispatchInfo.Capture(e).Throw(); return(default);
private Uri BuildRequestUri(string uri, NameValueCollection?queryParameters = null, RequestOptions?requestOptions = default, string version = "2.5") { requestOptions ??= RequestOptions.Default; // create a new query string collection var parameters = HttpUtility.ParseQueryString(string.Empty); // add query parameters if specified if (queryParameters != null) { parameters.Add(queryParameters); } // add the api key to the query parameter list parameters.Add("APPID", _options.ApiKey); // add the specific unit if it is not the default (Kelvin) if (requestOptions.Unit != UnitType.Default) { parameters.Add("units", requestOptions.Unit == UnitType.Imperial ? "imperial" : "metric"); } // add the specific language when specified if (!string.IsNullOrWhiteSpace(requestOptions.Language)) { parameters.Add("lang", requestOptions.Language); } // build request uri var query = parameters.ToString(); var requestUri = new Uri(_options.BaseAddress, version + "/" + uri); var builder = new UriBuilder(requestUri) { Query = query }; return(builder.Uri); }
public static UriBuilder AddQuery(this UriBuilder builder, NameValueCollection?nvc) { if (nvc == null) { return(builder); } //var query = string.Join("&", val.AllKeys.Select(key => // $"{WebUtility.UrlEncode(key)}={WebUtility.UrlEncode(val[key])}")); var query = string.Join("&", nvc.AllKeys.SelectMany(key => (nvc.GetValues(key) ?? Enumerable.Empty <string>()).Select(val => string.Concat(key, "=", WebUtility.UrlEncode(val))))); if (builder.Query.Length > 1) { builder.Query = builder.Query.Substring(1) + "&" + query; } else { builder.Query = query; } return(builder); }
public static bool TryParseForManagedIdentity(string uriString, [NotNullWhen(true)] out Uri?eventHubNamespaceUri, [NotNullWhen(true)] out string?eventHubName, [NotNullWhen(true)] out string?managedIdentityId) { if (Uri.TryCreate(uriString, UriKind.Absolute, out Uri? uri)) { NameValueCollection?queryVariables = HttpUtility.ParseQueryString(uri.Query); if (queryVariables.Count > 0) { eventHubNamespaceUri = new Uri(uri.Scheme + Uri.SchemeDelimiter + uri.Host); eventHubName = queryVariables[EventHubNameOption]; managedIdentityId = queryVariables[ManagedIdentityIdOption]; if (!string.IsNullOrEmpty(eventHubName) && !string.IsNullOrEmpty(managedIdentityId)) { return(true); } } } eventHubNamespaceUri = null; eventHubName = null; managedIdentityId = null; return(false); }
/// <summary> /// 字符串转字典 /// </summary> public static Dictionary <TKey, TValue> ToDictionary <TKey, TValue>(this string queryString) where TKey : notnull { NameValueCollection? request = HttpUtility.ParseQueryString(queryString ?? string.Empty); Dictionary <TKey, TValue> data = new Dictionary <TKey, TValue>(); if (request == null) { return(data); } foreach (string?key in request.AllKeys) { if (key == null) { continue; } TKey tKey = key.GetValue <TKey>(); string value = request?[key] ?? String.Empty; if (!data.ContainsKey(tKey)) { data.Add(tKey, value.GetValue <TValue>()); } } return(data); }
/// <summary> /// 格式化异常信息 /// </summary> /// <param name="exception"></param> /// <param name="collection"></param> /// <returns></returns> public static MarkupString FormatMarkupString(this Exception exception, NameValueCollection?collection = null) { var message = Format(exception, collection); return(new MarkupString(message.Replace(Environment.NewLine, "<br />"))); }
/// <summary> /// Sends a web request to an internet server. /// </summary> /// <param name="url">The URL where to send the request.</param> /// <param name="method">The web request method: GET or POST.</param> /// <param name="requestContent">The content of the web request.</param> /// <param name="contentType">The content type to include in the request header.</param> /// <param name="headers">Additional headers to include in the request.</param> /// <returns>The server's response.</returns> /// <exception cref="WebException">There was a communication error during the request.</exception> public async Task <string> ServerRequestAsync(Uri url, string requestContent = "", string method = "GET", string contentType = "", NameValueCollection?headers = null) { // ServicePointManager.Expect100Continue = false; // ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true; // Initialize client var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.ContentType = contentType; if (headers != null) { request.Headers.Add(headers); } if (!string.IsNullOrEmpty(requestContent)) { // Call method and get result using var rs = await request.GetRequestStreamAsync().ConfigureAwait(false); var requestBytes = Encoding.UTF8.GetBytes(requestContent); await rs.WriteAsync(requestBytes, 0, requestBytes.Length).ConfigureAwait(false); } // Read server response. using var response = await request.GetResponseAsync().ConfigureAwait(false); using var responseStream = response.GetResponseStream(); using var reader = new StreamReader(responseStream); var result = await reader.ReadToEndAsync().ConfigureAwait(false); return(result); }
/// <summary> /// Initializes a new instance of the <see cref="LavalinkCache"/> class using a new <see /// cref="MemoryCache"/> with the specified <paramref name="name"/>. /// </summary> /// <param name="name">the name of the <see cref="MemoryCache"/></param> /// <param name="config">an optional configuration entry collection for the <see cref="MemoryCache"/></param> public LavalinkCache(string name, NameValueCollection?config = null) : this(new MemoryCache(name, config), dispose : true) { }
private static void CollectServerVariables(Data rollbarData, NameValueCollection?serverVariables) { try { if (serverVariables != null) { // try harvesting Person DTO info: ////////////////////////////////// string[] serverVarsOfInterest = new[] { "AUTH_USER", "LOGON_USER", "REMOTE_USER", }; string?username = null; foreach (var serverVar in serverVarsOfInterest) { try { username = serverVariables[serverVar]; } catch { // calls in try-block may throw an exception. we are just trying our best... } if (!string.IsNullOrWhiteSpace(username)) { break; } } if (!string.IsNullOrWhiteSpace(username)) { rollbarData.Person = new Person(username !) { UserName = username !, }; } // try harvesting Server DTO info: ////////////////////////////////// var host = serverVariables.Get("HTTP_HOST"); if (string.IsNullOrEmpty(host)) { host = serverVariables.Get("SERVER_NAME"); } var root = serverVariables.Get("APPL_PHYSICAL_PATH"); if (string.IsNullOrEmpty(root)) { root = HttpRuntime.AppDomainAppPath ?? Environment.CurrentDirectory; } var machine = Environment.MachineName; var webServer = serverVariables["SERVER_SOFTWARE"]; if (!string.IsNullOrWhiteSpace(host) || !string.IsNullOrWhiteSpace(root) || !string.IsNullOrWhiteSpace(machine) || !string.IsNullOrWhiteSpace(webServer) ) { rollbarData.Server = new Server { Host = host, Root = root, }; rollbarData.Server["host_machine"] = machine; rollbarData.Server["host_webserver"] = webServer; } } else if (!HostingEnvironment.IsHosted) { // try harvesting Person DTO info (from Environment): ///////////////////////////////////////////////////// rollbarData.Person = new Person($"{Environment.MachineName}\\{Environment.UserName}") { UserName = Environment.UserName, }; } } catch { // calls in try-block may throw an exception. we are just trying our best... } }
/// <summary> /// UNSTABLE API. Creates a new scheduler configuration to build desired setup. /// </summary> /// <param name="properties">Base properties, if any.</param> /// <returns>New scheduler builder instance that can be used to build configuration.</returns> public static SchedulerBuilder Create(NameValueCollection?properties = null) { return(new SchedulerBuilder(properties)); }
protected SchedulerBuilder(NameValueCollection?properties) : base(properties ?? new NameValueCollection()) { }
/// <summary> /// Sends a POST web request to an internet server. /// </summary> /// <param name="url">The URL where to send the request.</param> /// <param name="requestContent">The content of the web request.</param> /// <param name="contentType">The content type to include in the request header. Default is "application/x-www-form-urlencoded".</param> /// <param name="headers">Additional headers to include in the request.</param> /// <returns>The server's response.</returns> public async Task <string> ServerPostAsync(Uri url, string requestContent = "", string contentType = "application/x-www-form-urlencoded", NameValueCollection?headers = null) { return(await ServerRequestAsync(url, requestContent, "POST", contentType, headers).ConfigureAwait(false)); }
/// <summary> /// Override. /// </summary> public override void Initialize(string?name, NameValueCollection?config) { base.Initialize(ApplicationName, config); }
/// <summary>The to dictionary.</summary> /// <param name="nvc">The nvc.</param> /// <returns>The Dictionary{string, string}.</returns> /// <exception cref="ArgumentNullException"><paramref name="nvc" /> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">keySelector produces duplicate keys for two elements.</exception> /// <exception cref="NotSupportedException">The collection is read-only and the operation attempts to modify the collection.</exception> public static Dictionary <string, string> ToDictionary(this NameValueCollection?nvc) => nvc is null ? throw new ArgumentNullException(nameof(nvc))
/// <summary> /// Perform a request to the Steam WebAPI service /// </summary> /// <param name="url">API url</param> /// <param name="method">GET or POST</param> /// <param name="data">Name-data pairs</param> /// <param name="cookies">current cookie container</param> /// <returns>response body</returns> static string Request(string url, string method, NameValueCollection?data = null, CookieContainer?cookies = null, NameValueCollection?headers = null, int timeout = 0) { // create form-encoded data for query or body string query = (data == null ? string.Empty : string.Join("&", Array.ConvertAll(data.AllKeys, key => String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key]))))); if (string.Compare(method, "GET", true) == 0) { url += (url.IndexOf("?") == -1 ? "?" : "&") + query; } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => { return(true); }); // call the server //HttpWebRequest request = GeneralHttpClientFactory(url); var request = GeneralHttpClientFactory.Create(url); request.Method = method; request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; request.ServicePoint.Expect100Continue = false; request.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; request.Referer = COMMUNITY_BASE; // + "/mobilelogin?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client"; if (headers != null) { request.Headers.Add(headers); } if (cookies != null) { request.CookieContainer = cookies; } if (timeout != 0) { request.Timeout = timeout; } if (string.Compare(method, "POST", true) == 0) { request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.ContentLength = query.Length; StreamWriter requestStream = new StreamWriter(request.GetRequestStream()); requestStream.Write(query); requestStream.Close(); } try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { LogRequest(method, url, cookies, data, response.StatusCode.ToString() + " " + response.StatusDescription); // OK? if (response.StatusCode != HttpStatusCode.OK) { throw new WinAuthInvalidRequestException(string.Format("{0}: {1}", (int)response.StatusCode, response.StatusDescription)); } // load the response using (StreamReader responseStream = new StreamReader(response.GetResponseStream())) { string responseData = responseStream.ReadToEnd(); LogRequest(method, url, cookies, data, responseData); return(responseData); } } } catch (Exception ex) { LogException(method, url, cookies, data, ex); if (ex is WebException exception && exception.Response != null && ((HttpWebResponse)exception.Response).StatusCode == HttpStatusCode.Forbidden) { throw new WinAuthUnauthorisedRequestException(ex); } throw new WinAuthInvalidRequestException(ex.Message, ex); } }