Here's what PRO C# developers do to become super productive and avoid unnecessarily debugging codes

My top 10 C# snippets that I use in every project

Here's what PRO C# developers do to become super productive and avoid unnecessarily debugging codes
Photo by AltumCode / Unsplash

Introduction

The biggest secret that has helped me throughout my career in becoming proficient in over a dozen of programming languages and frameworks is through the use of snippets and templates rather than typing everything from scratch.

Here are the technologies I've learned professionally throughout the years:

IMPORTANT

It's essential for you to master the fundamentals of programming first such as variables, conditions, data structures etc... It's also recommended to read and understand the official documentation of the technology you want to learn.

BEFORE

I spent lots of time surfing different websites such as StackOverflow just to get snippets of codes. This took me additional time and effort.

AFTER

Whenever I need a piece of code:

  • I simply open a single document,
  • search for what I want
  • copy and paste the structure of the codes
  • Adapt them as needed

Case close.

No more time-wasting and unnecessary headaches.

EVEN BETTER

You can add the snippets directly in your IDE of choice. Or use autocompletion tools such as AutoHotKey.

Snippets

Here's a list of my most-used snippets.

1. How to read from a config file

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("config.json", optional: false);

IConfiguration config = builder.Build();

2. Read from yaml file

public static Dictionary<string, string> ReadYaml(string filePath)
{
    var yaml = new Dictionary<string, string>();
    var file = new FileInfo(filePath);
    if (!file.Exists)
    {
        throw new FileNotFoundException("File not found", filePath);
    }

    var input = new StringReader(File.ReadAllText(filePath));
    var yamlConfig = new YamlStream();
    yamlConfig.Load(input);

    var mapping = (YamlMappingNode)yamlConfig.Documents[0].RootNode;
    foreach (var entry in mapping.Children)
    {
        yaml.Add(entry.Key.ToString(), entry.Value.ToString());
    }

    return yaml;
}

3. How to read a file by name?

Make sure you copy the file to output, otherwise the file won’t be detected in the build directory.

public string ReadFile(string fileName)
{
    var path = Directory.GetCurrentDirectory();
    var filePath = Path.Combine(path, fileName);
    return File.ReadAllText(filePath);
}

4. How to read args passed in parameters?

public static string[] ReadArgs()
{
    var args = Environment.GetCommandLineArgs();
    return args.Skip(1).ToArray();
}

5. How to read Environment Variables?

public static string GetEnvironmentVariable(string name)
{
    return Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.User);
}

6. How to take screenshot of screen?

How to take a screenshot using Selenium?

void TakeScreenshot(string fileName)
{
    Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
    ss.SaveAsFile(fileName, ScreenshotImageFormat.Png);
}

7. How to connect to a SQL Database?

class MySqlDb
{
	public MySqlConnection connection;
	public MySqlCommand command;
	
	public MySqlDb()
	    {
	connection = new MySqlConnection("server=localhost;userid=root;password=root;database=test");
	command = connection.CreateCommand();
	    }
}

8. How to connect to a MongoDB instance?

class MongoDb
{
	public MongoClient client;
	public IMongoDatabase database;
	public IMongoCollection<BsonDocument> collection;
	
	public MongoDb()
	    {
	client = new MongoClient("mongodb://localhost:27017");
	database = client.GetDatabase("test");
	collection = database.GetCollection<BsonDocument>("test");
	    }
}

9. How to send an email?

public class SmtpClientHelper
{
    public static void SendEmail(string to, string subject, string body)
    {
        var smtpClient = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(Env.GetString("EMAIL_USERNAME"), Env.GetString("EMAIL_PASSWORD"))
        };

        using (var message = new MailMessage(Env.GetString("EMAIL_USERNAME"), to)
        {
            Subject = subject,
            Body = body
        })
        {
            smtpClient.Send(message);
        }
    }
}

10. How to generate a unique string?

string GetUniqueString()
{
    return Guid.NewGuid().ToString("N");
}

Bonus: How to generate a random number between a custom range?

public static int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

Grab your FREE copy of 50+ C# Code Snippets and Templates today: