Skip to content

Commit

Permalink
Fix AddQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
TheArcaneBrony committed May 2, 2024
1 parent ca63a0d commit e885d07
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
17 changes: 17 additions & 0 deletions ArcaneLibs/Extensions/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ public static TY GetOrCreate<TX, TY>(this IDictionary<TX, TY> dict, TX key, Func
return value;
}

public static TV? GetOrDefault<TK, TV>(this IDictionary<TK, TV> dict, TK key, TV? defaultValue = default) => dict.TryGetValue(key, out var value) ? value : defaultValue;

public static async Task<TV?> GetOrDefaultAsync<TK, TV>(this IDictionary<TK, TV> dict, TK key, Func<TK, Task<TV>> valueFactory, SemaphoreSlim? semaphore = null) {
if (semaphore is not null) await semaphore.WaitAsync();
if (dict.TryGetValue(key, out var value)) {
semaphore?.Release();
return value;
}

value = await valueFactory(key);
dict.TryAdd(key, value);
semaphore?.Release();
return value;
}

public static TV? GetOrNull<TK, TV>(this IDictionary<TK, TV> dict, TK key) => dict.TryGetValue(key, out var value) ? value : default;

public static bool StartsWith<T>(this IEnumerable<T> list, IEnumerable<T> prefix) {
var array = prefix as T[] ?? prefix.ToArray();
var prefixLen = array.Length;
Expand Down
12 changes: 7 additions & 5 deletions ArcaneLibs/Extensions/UriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ namespace ArcaneLibs.Extensions;

public static class UriExtensions {
public static Uri AddQuery(this Uri uri, string name, string value) {
var ub = new UriBuilder(uri);
var qs = HttpUtility.ParseQueryString(uri.Query);
qs[name] = value;
ub.Query = qs.ToString();
return ub.Uri;
var location = uri.OriginalString.Split('?')[0];
var query = uri.OriginalString.Split('?').Skip(1).FirstOrDefault();
var newQuery = HttpUtility.ParseQueryString(query ?? "");
newQuery[name] = value;
// Console.WriteLine("OriginalString: " + uri.OriginalString);

return new Uri(location + "?" + newQuery, uri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative);
}
}

0 comments on commit e885d07

Please sign in to comment.