Wednesday, August 9, 2017

Application Insights filter to Errors

Application insights is an AMAZING tool for monitoring your application. Using the
Microsoft.ApplicationInsights.TraceListener
package with
Microsoft.AspNet.WebApi.Tracing
captures a great deal of information automatically which has reduced my time to identify bugs dramatically.

The Analytics dashboard allows for quick and easy slicing and dicing of data collected. I recently needed to see all Error Traces and found it to be somewhat indirect. I was expecting severityLevel to be 'Error', but it was an integer. Looking at the TraceLevel enum, Error = 1 so maybe that would match. Nope. Error is 3. I imagine this matches something, but it was not obvious so here is how you can get all error traces in the last 24 hours:


// Find error traces in the past 24 hours
traces 
 | where timestamp > ago(24h) and severityLevel == 3

Monday, June 19, 2017

Disable windows defender on Azure VM

I created a development machine in azure using a VS2017 template. I needed to install a bunch of tools, but windows defender was running a slowed everything down. Typically I just press the Windows Key and search for "Defender Settings" to disable windows defender. However, I was not able to find a way in the VM so I found a power shell command to do it for me. Made installation much faster!


Set-MpPreference -DisableRealtimeMonitoring $true

Thursday, May 18, 2017

Build Agent building PCLs

I've recently been getting ready for product launch, including setting up automated deployment into our development environments. Because of a restriction on the unit tests in the project, we cannot use the hosted build agents available with Visual Studio Online. We have to host our own server and install the build agent there.

After following the instructions here Deploy an Agent on Windows, I found that the agent was responding to builds that were queued thru visual studio online. However, since my solution contained PCL projects, I was getting the following error:

Error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\Portable\v4.5\Microsoft.Portable.CSharp.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.


Googling did not reveal much information, but I eventually stumbled upon this blog post which indicated the need for PortableLibraryTools. Even today, after installing the MS Build Tools 2015, the targets were not available. Installing this with the /buildmachine switch removed the above errors.

Thursday, February 2, 2017

Disposing HttpRequestMessage

I've been working with HttpClient alot lately (oh, how I wish they created an interface for it....) and have noticed quite a few things come up.

Today I wanted to figure out if I actually need to worry about disposing an HttpRequestMessage which I create and use with HttpClient. Because I'm creating the instance directly and I know it's not a derived version (for example, passed into a method as an argument), I can confidently interrogate the circumstances under which it should be disposed.

If I were accepting it as an argument and was expected to control the rest of the objects lifetime, then I would say you *should* to dispose the HttpRequestMessage because you are expected to.

If you create one and use it, specifically with System.Net.Http.HttpClient, you do not actually need to dispose the request object assuming that you successfully call SendAsync and here's why.

I was looking into the corefx/HttpClient repo and in this case, there is a method that is called which disposes the content after reading the response (with a nice comment).


private void HandleFinishSendAsyncCleanup(HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
    try
    {
        // When a request completes, dispose the request content so the user doesn't have to. This also
        // helps ensure that a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages
        // that can also be sent only once).
        request.Content?.Dispose();
    }
    finally
    {
        if (disposeCts)
        {
     cts.Dispose();
        }
    }
}


This method is called in a finally block as part of sending the request so it should always get called even if there is an error. I'm not sure there's really anything else to dispose aside from the content so its probably good enough, but I couldn't find any information or source code to persuade me one way or another.

The helper methods for Post, Get, Delete, and Put do not wrap the newly created HttpRequest created in a using statement or make any additional attempt to dispose.

public Task GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
    return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}

public Task PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
    request.Content = content;
    return SendAsync(request, cancellationToken);
}

public Task PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri);
    request.Content = content;
    return SendAsync(request, cancellationToken);
}

public Task DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
    return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}


I was also looking into the mono version, which does not dispose the request message or its content for you.

So, if you are creating an HttpRequestMessage and passing that message to the SendAsync method of a System.Net.Http.HttpClient, you can rest assured that the request has been disposed for you. If you have reason to believe that an exception may be thrown between creating the message, and calling SendAsync, a using statement would ensure that it is disposed. HOWEVER, even in this case, the only thing that actually gets disposed is the Content property and of the standard content types, only StreamContent actually needs to be disposed. If you are using, say, StringContent, it does not need to be disposed anyway and therefore the message does not need to be disposed.

Again, if we were considering the case of accepting method parameters which we did not create, you can not make these assumptions, but for code which looks like this, you should be pretty safe!

/// <summary> Gets the single, shared HttpClient instance </summary>
protected HttpClient Client {get;}

public async Task<Order> GetOrder(string orderId)
{
    // this message will be dispose when SendAsync is awaited
    HttpRequestMessage getOrderMessage = new HttpRequestMessage(HttpMethod.Get, $"api/orders?orderId={orderId}");

    // there is not really a chance for an error here...
    using(HttpRepsonseMessage response = await this.Client.SendAsync(getOrderMessage))
    {
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsAsync<Order>();    
    }
}

Friday, August 12, 2016

It's Official - I Can Develop ASP.NET MVC Web Applications

Recently, I finally decided to go down and take the 70-486 Developing ASP.NET MVC Web Applications exam which is the second of three exams required to become a Microsoft Certified Software Developer (MCSD).

This exam was actually easier (for me, at least) than the 70-483 Programming in C# exam. If you have worked on an MVC project for 2+ years, this should be a piece of cake.

Tips:
  1. Carefully read each question
    For questions which were fill-in-the-blanks, often the answer would be obvious without needing to read the question (can answer purely based on syntax). However, there were cases where an answer to a given question would be revealed in sample code for another question.
  2. First Chance Exceptions
    I think this was the only topic I really did not have much experience with. Make sure you know what First Chance Exceptions are and how they work!
  3. Configuration File Security
    Make sure you understand how to secure parts of your configuration file (like connection strings).

Overall

If you have a few years experience working with MVC, this test will be a no-brainer. I was able to finish the exam in 45 minutes and for many of the questions, the answer was trivially obvious (based on syntax) or something that you really should know. I felt the breadth of topics was waaaay smaller than for the Programming in C# exam so studying was fairly easy. In this case, I am fairly confident that even without studying, I would have passed this exam with no problems.

Being the second of three exams, passing did not increase my standing as far as Certification Titles. With the first exam, I became an MCP. This exam, I remain an MCP. With the next exam (70-487 Developing Microsoft Azure and Web Services) I will achieve the Microsoft Certified Software Developer (MCSD) Title.

Happy Coding!

Friday, July 8, 2016

Knockout + Kendo UI Date Picker - Open To Specific Date without Selecting

Don't you just love working with 3rd party vendor controls? In this post, I want to look at how you can open a Kendo UI Date Picker to a specific date, without selecting the date.

The Problem

Let's say you are using Knockout with Kendo UI and the Knockout-Kendo bindings. Your view model has two properties, one for start date and one for end date.

class DateRange {
    start: KnockoutObservable;
    end: KnockoutObservable;  // end date is optional

    constructor(start?: Date, end?: Date){
        this.start = ko.observable(start);
        this.end = ko.observable(end);
    }
}


When the user selects a start date in the future (more specifically, a start date that requires calendar paging), then we want the end date calendar to open to the same date, but not select the end date because the end date is optional.

The following code does not work correctly. It seems that setting the value of the DateView does not set the value of the observable property bound to the calendar and you cannot re-select the selected date. Consider the following steps:
  1. Select Start Date of July 10th, 2016
  2. Open End Date Calendar; notice that July 10th is selected, but the DateRange.end observable is not set
  3. Attempt to select July 10th for end date; nothing happens

// DOES NOT WORK
<input class="form-control" data-bind="kendoDatePicker: { value: start, min: new Date() }" placeholder="Start Date* (mm/dd/yyyy)" />
<input class="form-control" data-bind="kendoDatePicker: { 
    value: end,
    min: new Date(),
    open: function(e){
        if(start() && !end()) {
            e.sender.dateView.value(start());
        }
    }
}" placeholder="End Date* (mm/dd/yyyy)" />


By setting the value to the desired date and back to null, the date becomes focused, but not selected. This allows re-selection of that date.

// WORKS - null out value again; it keeps focus but is not selected
<input class="form-control" data-bind="kendoDatePicker: { value: start, min: new Date() }" placeholder="Start Date* (mm/dd/yyyy)" />
<input class="form-control" data-bind="kendoDatePicker: {
    value: end,
    min: new Date(),
    open: function(e){
        if(start() && !end()) { 
            e.sender.dateView.value(start());
            e.sender.dateView.value(null);
        }
    }
}" placeholder="End Date* (mm/dd/yyyy)" />

Tuesday, June 14, 2016

Knockout Placeholder Select Binding

So, for whatever reason, the select tag does not support the placeholder attribute. If it did, I'm assuming that's what the Knockout binding for optionsCaption would end up setting. I tried a few approaches to get a placeholder effect from the select box and have a decent working example. Of course, as is true with most coding questions, I started with a quick search of stack overflow. I took the example that worked the best for my scenario and turned it into a knockout binding.
At first, I thought I should extend the existing select binding, however, I soon realized there is no select binding; it just uses value, options, optionsText, ... to accomplish its task. So, I looked into adjusting the optionsCaption binding, and saw that it is just part of the options binding and I followed suit.

ko.bindingHandlers.placeHolderSelect = {
    after: ['options', 'value', 'optionsCaption'],
    init: function (elem, value, allBindings, viewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(value());

        if (allBindings['has']('optionsCaption')) {
            var caption = $(elem).find('option[value=""]');

            if (options === 'required') {
                caption.prop('hidden', 'hidden');
                caption.prop('disabled', 'disabled');
            }

            var emptyClass = 'empty';
            $(elem).change(function() {
                if (!$(elem).val()) {
                    $(elem).addClass(emptyClass);
                } else {
                    $(elem).removeClass(emptyClass);
                }
            });
            $(elem).change();
        }
    }
}

To use this binding, simply add placeHolderSelect and set the value to either 'required' if the selection should not allow the caption to be re-selected or any other value if the caption should allow re-selection.

    <!-- Cannot re-select caption -->
    <select data-bind="options: myOptions, optionsCaption: 'Caption Text', placeHolderSelect: 'required'"></select>

    <!-- Can re-select caption -->
    <select data-bind="options: myOptions, optionsCaption: 'Caption Text', placeHolderSelect: false"></select>
Enjoy!