Remove boilerplate from your C# code.
dotnet add package antiboilerplate --version 1.2.0
Sprinkle some functional magic on your C# code
Map your object of type TIn
to type TOut
using the provided mapping function:
var httpRequest = someObject
.Map(o => JsonConvert.SerializeObject(o))
.Map(o => new StringContent(o, Encoding.UTF8, "application/json"))
.Map(o => new HttpRequestMessage(HttpMethod.Post,"chat.postMessage")
{
Content = o
});
Perform action on object before returning it.
public string CreateMessage(string data)
=> $"Some message: {data}".Then(s => Console.WriteLine(s));
Treat any object as a collection (typically to be able to use Linq).
var transformedArray = someArray
.Union(someObject.AsCollection())
.Select(x => doAMapping(x));
Perform an action on each element in an array (similar to foreach
).
new []{1, 2, 3}
.Select(x => x * x)
.Each(Console.WriteLine); // method group
Deconstruct arrays (C# 7).
var (lastName, firstName, _) =
"Chaplin, Charlie Spencer".Split(new[] {' ', ','},
StringSplitOptions.RemoveEmptyEntries);
if (someString.IsNullOrEmpty())
{
...
}
if (someString.IsNullOrWhitespace())
{
...
}
Example: creating a basic authorization header.
var authorizationHeader = "Basic "
+ $"{username}:{password}".ToUtf8Base64()
Example: decoding a basic authorization header. (Including array deconstruction)
var (username, password) = authorizationHeader
.FromUtf8Base64()
.Split(':');
Handle disposable objects without using unnecessary variables.
var text = Disposable.Using(() => File.OpenText("somefile.txt"), file => file.ReadToEnd());
Instead of:
string text;
using (var file = File.OpenText("somefile.txt"))
{
text = file.ReadToEnd();
}
Read an embedded resource:
var data = await EmbeddedResource.Read("Antiboilerplate.tests.TestData.ConfigurationTestData.json",
Assembly.GetExecutingAssembly());
Read a Json file by naming convention. Add a marker type in with the same name and in the same namespace as the embedded resource:
// Declare type in the same namespace as ConfigurationTestData.json
internal class ConfigurationTestData {}
...
string data = await EmbeddedResource.ReadJson<ConfigurationTestData>();
As above, but parse the Json file using DataContractJsonSerializer
:
ConfigurationTestContents config = await EmbeddedResource.ReadAndDeserializeJson<ConfigurationTestData, ConfigurationTestContents>();
Reads and parses and XML file:
XDocument data = await EmbeddedResource.ReadXml<XmlTestData>();
Parse the query from a URI:
IDictionary<string,string> query = new Uri("http://host/path?a=1&b=2").ParseQuery();
var a = query["a"]; // => 1
Parse the query from a string:
IDictionary<string,string> query = "http://host/path?a=1&b=2".ParseQuery();
var a = query["a"]; // => 1
Create URI from string:
Uri uri = "http://host/path?a=1&b=2".ToUri();