Here's something kind of fun. In my web app, I want to know when certain things happen. Of course, I'm using Google Analytics with events and stuff, but sometimes, I want to know what's going on in real-time. Like, when a new account is created, or when someone makes a sale on my app.

I decided to do something that's not really practical in the long run, but works for now while my app is small and doesn't have a lot of traffic. When something interesting happens on my app, I fire a notification to a slack channel that I set up for this purpose. It's amazingly simple. This code was found on another blog post but I can't remember where. If you wrote that post, thanks.

Anyway, if you want to do something similar, it's really easy. Just create an app in Slack. Once that's done, you'll get an API URL for your app that looks like this: https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX

Now, all you have to do is POST to it using your channel name, URL and username with a simple client like this:

public interface ISlackClient
    {
        Task<HttpResponseMessage> SendMessageAsync(string message);
    }

    public class SlackClient : ISlackClient
    {
        private readonly Uri _webhookUrl;
        private readonly string _slackChannel;
        private readonly string _userName;
        private readonly HttpClient _httpClient = new HttpClient();
        
        public SlackClient()
        {
            _webhookUrl = new Uri(Environment.GetEnvironmentVariable("Slack_Notify_Url"));
            _userName = "someusername";
            _slackChannel = Environment.GetEnvironmentVariable("Slack_Notify_Channel");
        }
 
        public async Task<HttpResponseMessage> SendMessageAsync(string message)
        {
            var payload = new
            {
                text = message,
                _slackChannel,
                _userName
            };
            
            var serializedPayload = JsonConvert.SerializeObject(payload);
            var response = await _httpClient.PostAsync(_webhookUrl,
                new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
 
            return response;
        }
    }

You end up with some handy notifications:
Screen-Shot-2018-07-27-at-11.20.44-PM

Of course, if my app ever starts to get serious traffic, I'll turn this off and track these events in a better way, but for now, since I'm just starting out, this is pretty helpful.