Skip to content

Instantly share code, notes, and snippets.

@osisdie
osisdie / LazySingleton<T>.cs
Last active June 15, 2019 12:03
[C# .NET Standard 2.0+] Lazy singleton base class, supporting generic type
/// <summary>
/// Lazy Singleton (abstract base class)
/// </summary>
/// <typeparam name="T">Generic instance type</typeparam>
public abstract class LazySingleton<T> where T : LazySingleton<T>, new()
{
/// <summary>
/// Interlocked maximum initialized number
/// </summary>
const int MaxInitializedCount = 1;
@osisdie
osisdie / JObjectExtension.cs
Last active June 21, 2019 02:39
[C# .NET Standard 2.0+] Traverse JObject to get specific JToken value or dump all into Dictionary
// Idea from Node.js https://www.npmjs.com/package/nconf package
public static class JObjectExtension
{
public const string GoNextHierarchyDivider = ":"; // COLON
public const string ArrayElementAppender = ","; // COMMA
public static Dictionary<string, string> ToDictionary(this JObject src)
{
var result = new Dictionary<string, string>();
DeepParse(src, result);
@osisdie
osisdie / StringConvertingExtension.cs
Last active June 15, 2019 12:41
[C# .NET Standard 2.0+] Extension for converting string to bool, number
public static readonly string[] TrueStrings = { "1", "t", "y", "yes", "true", "on" };
public static readonly string[] FalseStrings = { "0", "f", "n", "no", "false", "off" };
public static bool ConvertToBool(this string src, bool defaultVal = false)
{
if (string.IsNullOrWhiteSpace(src))
{
return defaultVal;
}
@osisdie
osisdie / 01_ServiceReturn<T>.cs
Last active September 12, 2019 03:51
[c# .NET Standard 2.0] General generic result model after function, procedure, service call
// Idea from https://github.com/shshshdy/TopSdk.NetCore-Master/tree/master/TopSdk.NetCore
/// <summary>
/// Usage: The generic type could be primitive type or object type, to store actual return data
/// Wraper a ReturnBase model so we could give extra information, such as IsSuccess, Code, etc
/// Example:
/// ServiceReturn<bool>
/// ServiceReturn<Account>
/// ServiceReturn<Dictionary<string,string>>
/// </summary>
@osisdie
osisdie / 01_HttpPostAsync<T>.cs
Last active September 12, 2019 03:48
[C# .NET Standard 2.0] AsyncHttpPost supports generic response type
/// <summary>
/// Http POST method with contet-type = application/json
/// Get Raw response
/// </summary>
/// <param name="url"></param>
/// <param name="jsonData"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static async Task<ServiceResult<string>> HttpPostAsync(string url, string jsonData, IDictionary<string, string> headers = null)
{
@osisdie
osisdie / ModelValidation.cs
Last active June 20, 2019 12:49
[C# .NET Standard 2.0]
public static ServiceReturn<List<string>> Validate(object o, bool throwIfInvalid = false)
{
var context = new ValidationContext(o, null, null);
var validationResults = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(o, context, validationResults, true);
if (false == isValid && throwIfInvalid)
{
throw new Exception(string.Join(" ", validationResults));
}
@osisdie
osisdie / AsyncHttpPhotoDownload_Test.cs
Last active April 27, 2020 06:01
[C# .NET Standard 2.0] Async http download a dummy-photo data bytes
[TestClass]
public class AsyncHttpPhotoDownload_Test
{
[TestMethod]
public async Task Download_ToFile_Test()
{
var randomPhotoUrl = "https://dummyimage.com/600x400/000/fff";
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.png");
using (WebClient webClient = new WebClient())
{
@osisdie
osisdie / 01_AutoMapping_Test.cs
Last active September 12, 2019 01:48
[C# .NET Standard 2.0+] AutoMapping fat city array list data into simplified city array list
public class AutoMapping_Test : TestBase
{
[Fact]
public async Task CityDeserialize_MappingDTO_Test()
{
var rawUrl = "https://raw.githubusercontent.com/donma/TaiwanAddressCityAreaRoadChineseEnglishJSON/master/AllData.json";
var getResult = await NetworkUtility.HttpGet(url: rawUrl, headers: null, timeoutSecs: 30);
Assert.True(getResult.IsSuccess);
Assert.NotNull(getResult.Data);
@osisdie
osisdie / 01_dockerbuild.sh
Last active September 12, 2019 01:46
[C# .NETCore 2.2] Deploy -> ECR -> ECS via aws-cli and private azure feed
#!/bin/bash
APP_NAME=${APP_NAME:-"____________"}
ECR_HOST=${ECR_HOST:-"${APP_NAME}.dkr.ecr.us-west-2.amazonaws.com"}
REPO=${ECR_HOST}/${APP_NAME}
CONFIGURATION=${CONFIGURATION:-Release}
VERSION=${VERSION:-1.0.0.0}
NUGET_USERNAME=${NUGET_USERNAME:-""}
NUGET_ENDPOINT=${NUGET_ENDPOINT:-"https://pkgs.dev.azure.com/${APP_NAME}/_packaging/xxxxxxxxxxxx.Nuget/nuget/v3/index.json"}
NUGET_PAT=${NUGET_PAT:-""}
TAG=${REPO}:${VERSION}
@osisdie
osisdie / 01_azure-pipelines_netcore3-1.yml
Last active December 9, 2019 06:53
[.Net Core 3.1] Azure pipeline CI with private azure nuget feed
# ASP.NET Core
# Build and test ASP.NET Core projects targeting .NET Core.
# Add steps that run tests, create a NuGet package, deploy, and more:
# https://docs.microsoft.com/en-us/azure/devops/pipelines/ecosystems/dotnet-core?view=azure-devops
name: "Build API & UnitTest"
trigger:
branches:
include:
- feat/*