Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Convert object to csharp object initialization code

Below is a class that will convert any object into c# code that would statically initialize that object.

Why is this cool? - Suppose you need to write unit tests for a web service with quite complex structures (I'm looking at you swift/iso22000). Manually coding data into tests could take quite a while but if you already have some examples from logged requests or sample XML files you could use something like the below class to emit c# object initialization code and BAM your template code is written.

public static class ObjectInitializationSerializer
{
    private static string GetCSharpString(object o)
    {
        if (o is bool)
        {
            return $"{o.ToString().ToLower()}";
        }
        if (o is string)
        {
            return $"\"{o}\"";
        }
        if (o is int)
        {
            return $"{o}";
        }
        if (o is decimal)
        {
            return $"{o}m";
        }
        if (o is DateTime)
        {
            return $"DateTime.Parse(\"{o}\")";
        }
        if (o is Enum)
        {
            return $"{o.GetType().FullName}.{o}";
        }
        if (o is IEnumerable)
        {
            return $"new {GetClassName(o)} \r\n{{\r\n{GetItems((IEnumerable)o)}}}";
        }

        return CreateObject(o).ToString();
    }

    private static string GetItems(IEnumerable items)
    {
        return items.Cast().Aggregate(string.Empty, (current, item) => current + $"{GetCSharpString(item)},\r\n");
    }

    private static StringBuilder CreateObject(object o)
    {
        var builder = new StringBuilder();
        builder.Append($"new {GetClassName(o)} \r\n{{\r\n");

        foreach (var property in o.GetType().GetProperties())
        {
            var value = property.GetValue(o);
            if (value != null)
            {
                builder.Append($"{property.Name} = {GetCSharpString(value)},\r\n");
            }
        }

        builder.Append("}");
        return builder;
    }

    private static string GetClassName(object o)
    {
        var type = o.GetType();

        if (type.IsGenericType)
        {
            var arg = type.GetGenericArguments().First().Name;
            return type.Name.Replace("`1", $"<{arg}>");
        }

        return type.Name;
    }

    public static string Serialize(object o)
    {
        return $"var newObject = {CreateObject(o)};";
    }
}

How to send an email using Gmail and c#

How you can sent an email in c # using Gmail's SMTP servers. The only trick here is that Gmail requires you  to use port 587, enable SSL and supply valid login details.

            var client = new SmtpClient("smtp.gmail.com"587)
            {
                Credentials = new NetworkCredential("[valid Gmail username]""[valid Gmail password]"),
                EnableSsl = true
            };
            client.Send("[email from address]""[email to addression]""[email subject]""[email body]");

Using linq to read csv file

Alternative title: Fastest way to read a csv file into objects

Alternative title 2: Its only one line of code!

File.ReadAllLines("Employees.csv")
                        .Select(x => x.Split(','))
                        .Select(x =>
                             new EmployeeObject
                             {
                                 FirstName=x[0],
                                 LastName=x[1],
                                 DateOfBirth=DateTime.Parse(x[2]),
                                 Department=x[3]
                             });

How to get version number of assembly

Assembly.GetEntryAssembly().GetName().Version.ToString()

OR

FileVersionInfo.GetVersionInfo("").ToString()