Thursday, January 17, 2019

Random Cheatsheet (mostly C# .net core)

Latest endpoint to connect Visual Studio to the repository is

.Net Core 2.0, to include an HTML fragment into a .cshtml page:

    @await Html.PartialAsync("~/Views/Shared/_Address.cshtml")

To prepare for Dependency Injection in .Net Core 2.0

public void ConfigureServices(IServiceCollection services)
     services.AddSingleton(provider => Configuration);
     services.AddTransient<IUserRepository, UserRepository>();
     services.AddSingleton<IMailer, SmtpMailer>();

How to convert a json string to a C# Object

var myObject= JsonConvert.DeserializeObject(jsonString);

How to create a log4net factory outside of Startup.cs for unit testing.

public static ILoggerFactory GetLoggerFactory()
    var loggerFactory = new LoggerFactory();
    loggerFactory.AddProvider(new Log4NetProvider());

    return loggerFactory;

Create simple Moq object in C#

var imailerMoq = new Mock();
imailerMoq.Setup(x => x.SendEmail(It.IsAny(), It.IsAny())).Returns(true);

How to return async task for a unit test

public async Task GetAwesomeString() {
   return await Task.FromResult("I'm the awesome returned text");

sudo -s //makes the entire session root

In C# you cannot downcast an object, only cast an object upwards:

wrong    Sheep sheep = (sheep)mammal;
right  Mammal mammal = (Mammal)sheep;

C# -- to get prettyprint of json object with indentation:

var json = JsonConvert.SerializeObject(myObject, Formatting.Indented);

C# to get a key from a value:

Dictionary dictionary = GetMyDictionary();
var name = dictionary.FirstOrDefault(x => x.Value == id).Key;

To change the prompt in linux:

echo "PS1='\w\$ '" >> ~/.bash_profile; source ~/.bash_profile

No comments: