• Stars
    star
    195
  • Rank 199,374 (Top 4 %)
  • Language
    C#
  • License
    MIT License
  • Created over 6 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Utility class packages used at Stack Exchange...but on NuGet!

Stack Exchange Utility Packages

Home for the StackExchange.Util.* packages.

StackExchange.Utils.Http

Http is a helper class for making HttpClient calls. The send, deserialization, options, and verb portions are exchangable. Some examples:

POSTing a string and expecting a string:

var result = await Http.Request("https://example.com")
                       .SendPlaintext("test")
                       .ExpectString()
                       .PostAsync();

POSTing JSON and expecting protobuf back:

var result = await Http.Request("https://example.com")
                       .SendJson(new { name = "my thing" })
                       .ExpectProtobuf<MyType>()
                       .PostAsync();

Sending nothing and GETing JSON back:

var result = await Http.Request("https://example.com")
                       .ExpectJson<MyType>()
                       .GetAsync();

Sending nothing and GETing JSON back, with a timeout, ignoring 404 responses:

var result = await Http.Request("https://example.com")
                       .IgnoredResponseStatuses(HttpStatusCode.NotFound)
                       .WithTimeout(TimeSpan.FromSeconds(20))
                       .ExpectJson<MyType>()
                       .GetAsync();
// Handle the response:
if (result.Success)
{
    //result.Data is MyType, deserialized from the returned JSON
}
else
{
    // result.Error
    // result.StatusCode
    // result.RawRequest
    // result.RawResponse
}

Profiling

There are settings (.ProfileRequest and .ProfileGeneral) specifically for profiling - these are used and disposed around the events. By implementing IDisposable in something, you can time the events.

If you're using something like MiniProfiler, you can instrument HTTP calls in the default settings, like this:

var settings = Http.DefaultSettings;
settings.ProfileRequest = request => MiniProfiler.Current.CustomTiming("http", request.RequestUri.ToString(), request.Method.Method);
settings.ProfileGeneral = name => MiniProfiler.Current.Step(name);

StackExchange.Utils.Configuration

StackExchange.Utils.Configuration is a helper library that performs substitution and prefixing for IConfiguration-based configuration sources. It allows a value in the configuration tree to reference other values within the configuration system using a placeholder syntax ${key} or ${nested:key}. In addition, prefixing allows a "namespace" prefix to be applied to a subset of configuration, making it possible to segment configuration into logical areas.

This is particularly useful for storing secrets in a different, secure location but in a way that it makes it easy to compose configuration values like connection strings without dealing with it inside the application. E.g. consider the following files:

appsettings.json

{
    "ConnectionStrings": {
        "Database": "Server=srv01;Database=db01;User ID=${secrets:Database:UserId};Password=${secrets:Database:Password}"
    }
}

secrets.json

{
    "Database": {
        "UserId": "User123",
        "Password": "Password123!"
    }
}

This instructs the substitution provider to lookup the keys secrets:Database:UserId and secrets:Database:Password from the configuration system and replaces them in the value returned for ConnectionStrings:Database.

To support this a ConfigurationBuilder is configured as follows:

var configuration = new ConfigurationBuilder()
    .WithPrefix(
        "secrets",
        // everything in this configuration builder will be prefixed with "secrets:"
        c => c.AddJsonFile("secrets.json")
    )
    .WithSubstitution(
        // values in this configuration builder will have substitutions
        // replaced prior to being returned to the caller
        c => c.AddJsonFile("appsettings.json")
    )
    .Build();

Here we're loading a JSON file called secrets.json (it could equally be any source supported by the IConfiguration system - ideally something secure like Azure KeyVault or Hashicorp's Vault) and prefixing it with secrets:. Then, we load appsettings.json with support for substitutions. If a caller asks the IConfiguration that is produced for a connection string:

var connectionString = configuration.GetConnectionString("Database");

That value will be returned as Server=srv01;Database=db01;User ID=User123;Password=Password123!.

#### Substituting existing values In some cases it's useful to be able to substitute placeholders in existing strings. Support for that is provided by the SubstitutionHelper:

var configuration = new ConfigurationBuilder()
    .WithPrefix(
        "secrets",
        // everything in this configuration builder will be prefixed with "secrets:"
        c => c.AddJsonFile("secrets.json")
    )
    .Build();

var value = "Server=srv01;Database=db01;User ID=${secrets:Database:UserId};Password=${secrets:Database:Password}";
var valueWithSubstitution = SubstitutionHelper.ReplaceSubstitutionPlaceholders(value, configuration);

This will do exactly the same as if the value was substituted within the configuration system itself - the returned value will be Server=srv01;Database=db01;User ID=User123;Password=Password123!.

Notes

If a value has substitution placeholders that could not be replaced they are left intact - only placeholder keys that can be located in the configuration system are replaced.

License

StackExchange.Utils is licensed under the MIT license.

More Repositories

1

blackbox

Safely store secrets in Git/Mercurial/Subversion
Go
6,670
star
2

StackExchange.Redis

General purpose redis client
C#
5,889
star
3

dnscontrol

Infrastructure as code for DNS!
Go
3,043
star
4

NetGain

A high performance websocket server library powering Stack Overflow.
C#
933
star
5

Stacks

Stack Overflow’s Design System
Less
610
star
6

wmi

WMI for Go
Go
433
star
7

pagedown

The Markdown editor and converter used on Stack Overflow and the other Stack Exchange sites
JavaScript
419
star
8

Stacks-Editor

Stack Overflow's Combination Rich Text / Markdown Editor
TypeScript
362
star
9

StackExchange.DataExplorer

Stack Exchange Data Explorer
JavaScript
353
star
10

MarkdownSharp

Open source C# implementation of Markdown processor, used by Stack Overflow.
C#
246
star
11

stack-blog

Stack Overflow Blog
HTML
238
star
12

httpunit

httpUnit tests compliance of web and net servers with desired output.
Go
164
star
13

StackExchange.Precompilation

Roslyn based csc.exe and aspnet_compiler.exe replacement with metaprogramming hooks for ASP.NET MVC projects from the pre-DNX era
C#
154
star
14

StackExchange.Metrics

A .NET client to send metrics to a variety of metrics backends
C#
136
star
15

Stacks-Icons

Authoring tools for Stack Overflow's shared icon set.
TypeScript
35
star
16

NRediSearch

C#
31
star
17

stackegg

The core game logic of Stack Overflow's April 1st 2015 game, StackEgg.
C#
30
star
18

mayflower

A simple MS SQL Server database migrator using Node.js and TDS.
JavaScript
26
star
19

StackID

An OpenID provider implemented for the Stack Exchange network, built on top of dotNetOpenAuth.
C#
20
star
20

stackexchange.github.com

Source for stackexchange.github.com
HTML
19
star
21

apca-check

Axe rules to check against APCA bronze and silver+ conformance levels.
TypeScript
18
star
22

unikong

Stack Overflow's April 1, 2016 game
JavaScript
16
star
23

haproxy-kubefigurator

Dynamic haproxy configuration for Kubernetes services
Go
14
star
24

RyuJIT-TailCallBug

Tail Call Parameter Corruption Repro for .Net 4.6
C#
12
star
25

signalfx-powershell

This is a PowerShell wrapper around the SignalFx API
PowerShell
10
star
26

mof

Package mof parses and marshals Managed Object Format (MOF) structures
Go
9
star
27

pat

A wrapper for "puppet agent --test"
Go
9
star
28

stackexchange-superfirewall

A facade for firewall::firewall{} that adds enhanced functionality.
Puppet
7
star
29

browserslist-viewer

Static site to parse and display a browserslist string
TypeScript
6
star
30

stacks-utils

A monorepo containing a collection of Stacks config files and other utilities
JavaScript
6
star
31

Stacks-TagHelpers

A set of .Net Core Tag Helpers for use with Stacks
C#
5
star
32

DesignSprint

This repository was used for building a Stack Overflow Talent exploratory design sprint.
HTML
2
star
33

terraform-provider-stackoverflow

Terraform Provider for Stack Overflow
Go
2
star
34

sre-log-1

1
star
35

marketing-resources

1
star