Thursday, December 29, 2016

Sending emails with .NET Core v1.1 and mailgun with attachements

I simply wanted to send some emails programmatically using .NET Core v1.1 with attachments.
Perhaps I should have chosen a different route, however I had already signed up for a 
mailgun account as it seemed like that would be the quickest and easiest way to do it.  
Perhaps it was... but it certainly wasn't very quick, and wasn't exactly easy; 
atleast not until I figured it out.  Now it seems super quick, and super easy.  

I hope this helps someone save some time.  Peace.

public static void SendEmailWithAttachement
(string emailTo, string emailSubject, string emailText, byte[] attachmentByteArray, string attachmentFileName)
            // the domain name you have verified in your Mailgun account
            const string DOMAIN = "";
            // your API Key used to send mail through the Mailgun API
            const string API_KEY = "key-mysupersecretkey";

            using (var client = new HttpClient())
                client.DefaultRequestHeaders.Authorization = 
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api" + ":" + API_KEY)));

                using (var content = new MultipartFormDataContent())
                    var values = new[]
                        new KeyValuePair<string, string>("from", "Jimmy Neutron <>"),
                        new KeyValuePair<string, string>("to", emailTo),
                        new KeyValuePair<string, string>("subject", emailSubject),
                        new KeyValuePair<string, string>("text", emailText)

                    foreach (var keyValuePair in values)
                        content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                    var fileContent = new ByteArrayContent(attachmentByteArray);//(System.IO.File.ReadAllBytes(fileName));
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        Name = "attachment",
                        DispositionType = "form-data",
                        CreationDate = DateTime.Now,
                        Size = attachmentByteArray.Length,
                        FileName = attachmentFileName,
content.Add(fileContent); var requestUri = "" + DOMAIN + "/messages"; var result = client.PostAsync(requestUri, content).Result; //TODO do something with the result... //like log it... or something dude. } } }

Monday, December 19, 2016

ASP.NET Core v1.1 inside a docker container connected to a containerized PostgreSQL database with Entity Framework v1.1

Running the latest dotnet core inside a docker container with entity framework code first hooked into a postgresql database (also in a container) was way harder for me than I think it should be.  So I wrote this blog to help others who may decide to go down this path.

I really just want to run the latest version dotnet core inside of a docker container and connect my code to a postgresql database using entity framework, and then update everything with migrations and 'update-database'.  You know, like back in the 'good ole days' when it was just plain ASP.NET MVC with EF hooked into a MS-SQL server database.  I suppose getting to a cross-platform codebase along with a sweet object relational mapper should be a little bit complex... but that doesn't mean it should be complicated.  However my goals were much more difficult to achieve than I first anticipated.

Once I figured out a mechanism that would work on my development machine (virtual machine running Windows) and something that would work on my production environment (linux [ubuntu 16.04] with docker) I wanted to make sure I created a 'kernel of truth' which could help others, and possibly myself in the future (I really never want to bang my head against the wall that hard again).

So, I created a project, which can be found on github:

And now I'll tell you a little bit about it.

Let's just get this out of the way.... I really do not know what I am doing... but I think this is correct.... I mean at least it works! Of course, the more I read the more about the state of ASP.NET Core v1.1 and EntityFramework Core v1.1, it becomes painfully obvious that at this point not many people are sure what is 'correct' (particularly the tools).  So it would appear I am in good company.  But I will give it a shot at explaining what I did.  Some things I've forgotten, some things I wish I could forget... but I digress.... on to it.

I downloaded the community version of Visual Studio 2017 RC and installed the dotnet core 1.1 SDK.  Then I tried to go -> file -> new project... This kind of works... but not really.  I proceed to update all the packages to v1.1 (instead of v1.0.1) and things are going a little bit better.  But honestly I'm not sure exactly how I ended up with a working project.... which is why I made this 'kernel of truth' project.  

My suggestion at creating a new v1.1 project is to copy the relevant parts of my kot.csproj and paste it into your .csproj.  One of the major issues of confusion is the switch from using project.json to now using project.csproj with msbuild.  Even more confusing is that the 'latest' docker container is still pointing to the project.json style, whereas I read project.json is history; and microsoft is moving to msbuild stuff.... which caused me all sorts of headaches, and I'm sure others too.

I used the package manager inside visual studio as sparingly as possible, and probably will try to steer clear of it, until later tool set upgrades.  Right now, I'm using the cmd line inside windows and bash shell inside of docker containers to call things like 'dotnet ef migrations add nameOfMigration*' and things like 'dotnet ef database update'.  Which is just fine with me, but can be a major source of confusion when you are used to doing everything inside of PM> (the package manager console inside visual studio) because at the moment there is no such console when on a linux machine (or even just using command prompt on windows).  It does appear that the CLI tools are moving toward allowing package manager type stuff, but we will still have to wait and see.  

Bottom line.  I can now spin up a virtual machine with docker installed and with a few commands (found in the project under: bashCommandsToSpinUp.txt) and have two docker containers running and communicating... one running code and the other running the database.  Hurray!!!

I know this blog may sound a bit contentious... I'm not actually upset with anything other than myself for having to spend so much time searching and trying various things to get this to work.  I hope this article (and more specifically the kot project) will help others spend far less time than I did, and get them back to doing productive code writing stuffs.

Peace homies.