-
Notifications
You must be signed in to change notification settings - Fork 2
/
Extensions.cs
60 lines (51 loc) · 1.72 KB
/
Extensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace CLARiNET
{
public static class Extensions
{
public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(
this IEnumerable<TSource> source, int batchSize)
{
var items = new TSource[batchSize];
var count = 0;
foreach (var item in source)
{
items[count++] = item;
if (count == batchSize)
{
yield return items;
items = new TSource[batchSize];
count = 0;
}
}
if (count > 0)
yield return items.Take(count);
}
public static void BasicAuth(this HttpRequestMessage http, string username, string password)
{
var authenticationString = $"{username}:{password}";
var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(authenticationString));
http.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64String);
}
public static string EscapeXml(this string xml)
{
return xml.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\"", """)
.Replace("'", "'");
}
public static TEnum ToEnum<TEnum>(this string value)
{
if (string.IsNullOrEmpty(value))
return default;
return (TEnum)Enum.Parse(typeof(TEnum), value, true);
}
}
}