Skip to content

Instantly share code, notes, and snippets.

View gsscoder's full-sized avatar
💭
obsessive coding disorder

coder (π³) gsscoder

💭
obsessive coding disorder
View GitHub Profile
@gsscoder
gsscoder / LowerCaseNamingStrategy.cs
Created July 9, 2020 09:02
C# Json.NET naming strategy to serialize enum values as lowercase strings
/*
public class YourClass
{
[JsonProperty("type")]
[JsonConverter(typeof(StringEnumConverter), converterParameters: typeof(LowerCaseNamingStrategy))]
public YourEnum YourProperty { get; set; }
}
*/
using Newtonsoft.Json.Serialization;
@gsscoder
gsscoder / RandomString.cs
Last active January 20, 2021 05:26
C# cryptographic random string generator
// Requires: https://github.com/gsscoder/csharpx
using System;
using System.Linq;
using CSharpx;
static class RandomString
{
const string _alphanumeric = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string _chars = "abcdefghijklmnopqrstuvwxyz0123456789!\"#$%&'()*@[\\]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZ";
@gsscoder
gsscoder / FeedIteratorExtensions.cs
Created June 23, 2020 11:53
C# extension method to copy all CosmosDB iterator items to a sequence
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
public static class FeedIteratorExtensions
{
public static async Task<IEnumerable<T>> ReadAllAsync<T>(this FeedIterator<T> iterator)
{
var result = new List<T>();
while (iterator.HasMoreResults) {
@gsscoder
gsscoder / DictionaryExtensions.cs
Last active June 22, 2020 09:52
Simple C# pure extension methods for dictionaries
using System.Collections.Generic;
public static class DictionaryExtensions
{
public static IDictionary<T, U> Merge<T, U>(this IDictionary<T, U> target, IDictionary<T, U> source)
{
var result = new Dictionary<T, U>(target);
foreach (var pair in target) {
if (source.ContainsKey(pair.Key)) {
result[pair.Key] = source[pair.Key];
@gsscoder
gsscoder / ObjectExtensions_ToDictionary.cs
Last active June 16, 2020 09:52
Simple C# extension method to serialize an object to a dictionary
using System.Collections.Generic;
public static class ObjectExtensions {
public static IDictionary<string, string> ToDictionary(this object obj) =>
ToDictionary<string>(obj);
public static IDictionary<string, T> ToDictionary<T>(this object obj)
{
var properties = obj.GetType().GetProperties();
@gsscoder
gsscoder / Get-TFRuns.ps1
Created June 2, 2020 05:34
PowerShell script to list Terraform Cloud runs
$token = '*************YOUR****TOKEN******HERE******************************************************'
$workspaceId = 'ws-bbaGwqP1yANww4va'
$response = Invoke-WebRequest -Uri "https://app.terraform.io/api/v2/workspaces/$workspaceId/runs" `
-Method Get `
-ContentType 'application/vnd.api+json' `
-Headers @{
Authorization = "Bearer $token"
} `
-UseBasicParsing
@gsscoder
gsscoder / DateHelper.ts
Last active May 28, 2020 15:53
TypeScript date helper functions
export class DateHelper {
public static getWeekDay(locale: string, day: number, format: string = 'long') {
if (day <=0 || day > 7) throw new Error('Invalid day number. Expected to be in range of 1-7.');
let baseDate = new Date(Date.UTC(2000, 0, 3)); // Monday
baseDate.setDate(baseDate.getDate() + day - 1);
return baseDate.toLocaleDateString(locale, { weekday: format });
}
public static getMonth(locale: string, month: number, format: string = 'long') {
if (month <=0 || month > 12) throw new Error('Invalid month number. Expected to be in range of 1-12.');
@gsscoder
gsscoder / Validation_helpers.ps1
Last active May 12, 2020 14:24
PowerShell validation helper functions
function Test-Url([Parameter(ValueFromPipeline)] [string] $url) {
$url -cmatch '^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$'
}
function Test-Guid([Parameter(ValueFromPipeline)] [string] $guid) {
try { [System.Guid]::Parse($guid) | Out-Null; $true } catch { $false }
}
function Test-IPAddress([Parameter(ValueFromPipeline)] [string] $ip, [switch] $cidr) {
if ($cidr) { $ip -match '^(?:\d{1,3}\.){3}\d{1,3}/\d\d$' }
@gsscoder
gsscoder / TypeSwitch_PatternMatching.cs
Last active May 4, 2020 05:20
Helper class that allows pattern matching on types
// Based on: https://docs.microsoft.com/en-gb/archive/blogs/jaredpar/switching-on-types
// Example:
// TypeSwitch.Do(propertyInfo.PropertyType,
// TypeSwitch.Case<bool>(() => value = property.Value.GetBoolean()),
// TypeSwitch.Case<int>(() => value = property.Value.GetInt32()),
// TypeSwitch.Case<long>(() => value = property.Value.GetInt64()),
// TypeSwitch.Case<double>(() => value = property.Value.GetDouble()),
// TypeSwitch.Case<string>(() => value = property.Value.GetString()),
// TypeSwitch.Default(() => throw new InvalidOperationException("Type is not supported.")));
@gsscoder
gsscoder / git-tag_helpers.sh
Created April 21, 2020 08:05
Two simple BASH scripts to add/remove Git tags from local/remote
# addtag.sh
###########
#!/bin/sh
git tag -a v$1 -m "Version $1" && git push origin --follow-tags
# rmtag.sh
##########
#!/bin/sh
git tag -d v$1 && git push origin -d v$1