Sunday, February 21, 2016

Hide Windows 10 useless folders

I just migrated over to a fresh development PC running Windows 10. It took many hours of work to remove most of the "junk" that clutters the desktop, processes and apps. I removed all tiles from the Start menu. I uninstalled every modern app that's possible (news, weather, sport, etc). I disabled services that will be unused. I disabled the firewall and Defender. Using Sysinternals tools I found startup items and running processes that were useless. And so on ... for hours. I still haven't figured out how to disable or remove Adobe Flash yet, but I swear I will, despite the fact they've baked it right into the operating system.

One challenge was to shrink the number of folders in Windows Explorer. You get a Quick access node at the top containing Desktop, Downloads, Documents, etc, but these folders are duplicated under This PC, which a dreadful waste of space. Web searches on this revealed lots of stupid and dangerous ideas, but finally I found a chap who correctly assumed that the appearance of the Windows Explorer tree was controlled by the Registry, and he found the correct keys to adjust and hide the useless folders. Look here with admin permissions:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft
  \Windows\CurrentVersion\Explorer\FolderDescriptions

Find the child Guid nodes containing a REG_SZ Name of the folders you want to hide. There will be a child key PropertyBag\ThisPCPolicy which you change from Show to Hide. One entry didn't have the ThisPCPolicy key and I had to add it manually.

Setting the values to Hide takes affect as soon as you relaunch Windows Explorer. You can see in this picture how I had removed a few folders and was about to remove the last two, leaving a much cleaner looking tree.


One overarching question needs to be asked here ... Why am I doing this? I'm not the only person who is "cleaning up" Windows 10 to remove all the clutter and junk. It hints that Microsoft's marketing and design departments are losing touch with reality. Overall, Windows is getting dumber and dumber, progressively looking and feeling more like an iMac (maybe that's what they want!).

There are so many subtle changes to Windows 10 that make life harder for power users and developers. Many actions and commands in Windows 7 require more mouse clicks, scrolling and navigation in Windows 10. I've been forced to pin many apps to the start bar or create desktop icons to allow quick Run as Administrator.

Addendum #1

While continuing to disinfect Windows 10 I stumbled across this fabulous article by Chris Hoffman which tells you how to use Powershell to uninstall the pesky modern apps like Camera, Groove Music, Get Skype, Music & TV, People, Weather, etc, that can't simply be uninstalled. The effect of running his commands is beautiful: all the built-in modern app garbage is erased. Once again ... why am I doing this?!

Addendum #2

I boot my PC the following morning and Windows 10 told me that updates had been installed and all my files were exactly where they used to be. The screen background had gone blank, and absolutely everything I did in the steps above had been undone. All folder icons and all Windows 10 apps had been restored.

Addendum #3

Someone in the forum has hinted that the reversal of my changes was an unfortunate coincidence, possibly caused by a major 10.1 automatic update. The update history has no entries to confirm this. My reapplied changes have been preserved for a couple of weeks now.

Sunday, February 14, 2016

Web API secret plumbing

August 2021 Note: Most of this post is no longer meaningful after the arrival of .NET Core with significant changes to the ASP.NET libraries. The note below about dropping WebForms and preferring MVC to write web apps is now completely outdated and redundant. The arrival of Blazor Webassembly has driven a stake into the heart of server-side ASP.NET apps. I can write a Blazor app in about one fifth the time and with one fifth the code compared to a similar ASP.NET app. Unfortunately, we are still stuck with ASP.NET Web API for RESTful data services (although Azure Function apps are a good alternative).


February 2017 Note : When I wrote this post a year ago I stated that I would not use ASP.NET MVC to write web applications, only WebAPI services. I have changed my mind and in future will drop WebForms and switch to MVC. I eventually got sick of the complicated pipeline of WebForms events and the lack of control over the rendered HTML, which is often an incomprehensible mess. I was also sick of getting hundreds of KB of ViewState for simple grids, and you can't disable the grid's ViewState or commands no longer fire.
However, if you create a skeleton MVC app from a Visual Studio 2015 template you get about 30 references to libraries and NuGet packages, most of which are JavaScript framework garbage. For a simple web app that needs little to no JavaScript you have to tediously remove packages and their dependencies in the correct order, then delete useless references and files. You can eventually strip the project down to a sensible size and start developing without all the clutter.

A few years ago I became fed-up with how complicated ASP.NET WebForms programming was. The pipeline of events is really long and delicate. If you do something in the wrong order you may get events that don't fire, controls that don't update, missing postback data, and so on. I've spent many tearful hours of my life trying to find out why a row click in a grid doesn't work to eventually discover I was doing something in the event handler that should have waited until PreRender, or vice versa. Another problem is the lack of control over formatting, exemplified by a tiny single-page app I wrote few months ago containing just a grid and a few buttons which renders an incomprehensible mess of html.

A few years ago, ASP.NET MVC was getting a lot of good comments and publicity so I ran the tutorials and bought some books in the hope that I would find the whole web programming model had been simplified with a tiny pipeline and you had more control over the rendered output. I found this to be generally true, but there was still "secret plumbing" all over the place. Magic values and naming conventions had simply replaced the difficulty of WebForms programming with a new type of mysterious difficulty. Everything I wanted to do in ASP.NET MVC required searching for a magical piece of plumbing that had to be named or registered.

After a few months I gave up in disgust at the prospect of using ASP.NET MVC. I just can't imagine what twisted minds can take something as simple as the http request-response model and wrap it in so many layers of complexity. I have been tempted at times to return to the early 1990s and write a web app with a single ashx handler file that takes the raw request and converts it into a raw response, thereby skipping all plumbing and frameworks.

Although I refuse to write web applications using ASP.NET MVC, I do write web services of the ASP.NET Web API variety which share a lot of coding style with MVC using routes and controllers. Even through the Web API is a stripped down MVC, it still unfortunately shares a fair amount of "secret plumbing" that you have to discover and use correctly. I have stumbled upon some important "secrets" which I'm putting in this post as a reminder to myself and anyone else who cares.

ActionFilterAttribute

Write a class that derives from ActionFilterAttribute and override OnActionExecuting and OnActionExecuted so you can automatically intercept the request and response of every API call. You can, for example, validate requests with code in a single place instead of spreading it all over the controller methods. You can extract request information like an auth token and place it in the request's property collection so it's handy at all times. Anything you want to intercept or do automatically on all API calls can be placed in your action filter class. Register the filter on controller methods like this example:

[HttpDelete]
[Route("")]
[MyActionFilter(...)]
public IHttpActionResult Delete()
{
  ...
}


You can pass parameters to the filter's constructor if it's useful.

ExceptionFilterAttribute

Write a class that derives from ExceptionFilterAttribute and override OnException to automatically intercept all errors without the need to spread try-catch code all over the controllers. You can log errors or transform them into different types of responses that are perhaps more friendly for callers of your API. You register the exception filter the same way as the action filter.

HttpParameterBinding

I uncovered this devious and tricky class while trying to automatically convert different types of query values into a controller method's bool parameter. It's quite sensible to allow API callers to specify a true/false value as Y, y, N, n, false, TRUE, 0, 1, and so on. I guessed there was a way of automatically coercing query values like &blah=1 or &blah=y into a bool value, but I had to find the secret plumbing that did this. An obscure hint in a web search pointed me to the HttpParameterBinding class, but further searches revealed ambiguous and confusing use of the class and the context parameters available to it. By trapping a call in the debugger I eventually managed to figure out just which context values were required to perform the transform I required. Here is the stripped down code that does what I want.

public override Task ExecuteBindingAsync(...)
{
  var dict = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
  string raw = dict[Descriptor.ParameterName];
  bool? value = null;
  if (Regex.IsMatch(raw ?? "", $"^(?:y|true|1)$", RegexOptions.IgnoreCase))
  {
    value = true;
  }
  else if (Regex.IsMatch(raw ?? "", $"^(?:n|false|0)$", RegexOptions.IgnoreCase))
  {
    value = false;
  }
  actionContext.ActionArguments.Add(Descriptor.ParameterName, value ?? Descriptor.DefaultValue);
  return Task.FromResult(0);
}


The raw string value named in Descriptor.ParameterName is parsed out of the request query string, inspected and transformed into the required bool value and placed in the actionContext.actionArguments collection for passing into the controller method. You can use this sort of parameter binding code to transform any incoming value into another type. You will need to create a small custom Attribute to apply your binding to a parameter, then use it like this:

internal class BoolBindingAttribute : ParameterBindingAttribute
{
  public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
  {
    return new BoolParameterBinding(parameter);
  }
}

public IHttpActionResult Foo([MyBoolBinding] bool blah)
{
  ...
}


So if a request contains &blah=1 it will be silently transformed into true.

AddQueryStringMapping

It is a web service convention that the response body format obey the Accept request header MIME type value. So for example sending the header Accept: application/xml will result in an XML response body. For the convenience of callers, and for easier testing, it's possible to map a query parameter to a MIME type. In the static WebApiConfig Register method, add lines like these popular examples:

config.Formatters.JsonFormatter.AddQueryStringMapping("format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("format", "xml", "application/xml");

You can then simply add ?format=xml to a request query to get the same effect as adding the corresponding request header.

WPF Binding Recommendations

I just audited the binding code in a reasonably large WPF application I wrote in July 2015 and was embarrassed to find lots of subtle bugs. Some controls were not bound to the specific properties they depended upon, some controls were bound to irrelevant or incorrect properties, and some binding properties were orphaned and unused.

The Visual Studio designer and the compiler can't fully bridge the gap between XAML and code, so human error is bound to creep in. You may accidentally cut-and-paste the same binding property into two different places, you may misspell a property, and so on. Many errors like this will not show up in the designer and you may only detect them by looking for binding error messages in the Visual Studio output window. Despite the danger of coding errors, I have set the following vague rules for myself to help binding work more reliably:
  1. Bind whenever it's possible.
  2. Put all binding logic in the converters.
  3. Don't forget to use the powerful MultiBinding.

When Possible

Although the syntax of binding is verbose and it's implementation is clumsy and incomplete, it's a great advance in the separation of business logic from UI behaviour. In the 1990s you could use MFC/C++ Data Exchange macros and classes in an attempt to move data in and out of the UI, but it was tedious and unnatural. In 2005 I participated in writing a huge Windows Forms app where we simulated WPF style binding in code. It generally worked, but the amount of code (and hacks) was staggering. A year later, Framework 3.0 and WPF were released, which made most of our WinForms code redundant. So modern binding is a great facility and you should use whenever possible.

Sometimes you'll find properties that can't be bound, a good example is the DataGrid's SelectedItems property. Some people use clever tricks like custom attached properties and behaviors to bind the unbindable, but I think this is overkill and I prefer to use a little bit of code-behind to fill the gap. With the DataGrid example I would do this:

private void Grid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  var selects = ((DataGrid)sender).SelectedItems.Cast<Foo>().ToArray();
  controller.SelectedFoos = selects;
}

Purists don't like any code-behind at all, but I think this is quite acceptable and easy to read. The SelectedFoos property on the controller participates in INotifyPropertyChanged so controls can bind to the property.

Use Converters

Always put the binding logic code inside value converter classes, don't be lazy and leave it in controllers. I used to do the following, if for example I wanted a control to be visible if Foo is not null:

public Foo SelectedFoo
{
  get { return _selfoo; }
  set
  {
    _selfoo = value;
    SendChange("SelectedFoo");
    SendChange("IsThingVisible");
  }
}

public Visibility IsThingVisible
{
  get { return _selfoo != null ? Visibility.Visible : Visibility.Collapsed; }
}

What I've done is make a fake binding property that converts null to a Visibility enum. This works and looks easy, but as the number of these fake properties grows, the relationships between them all gets confusing and errors can creep in. You must put this logic in a value converter where it's reusable and isolated, like this:

if (convertArg == "SomeToVisible")
{
  return value != null ? Visibility.Visible : Visibility.Collapsed;
}

Then the XAML to use this is something like:

Visibility="{Binding SelectedFoo,
    Converter={StaticResource MyConverter},
    ConverterParameter=SomeToVisible}"

You will probably find that a lot of binding logic simply converts between different types, so it can be packaged into neat groups in the type converter and reused throughout the XAML. The important thing is that all binding logic and conversion takes place inside your value converter classes.

Use MultiConverter

Like the sample above where I was lazy and put binding logic in the controller, I also fell into the bad habit of using fake properties to allow binding to multiple conditions. If for example I wanted a control to be visible if something is not null and a flag is false, I used to do this in the controller.

public List Foos
{
  ...
  set
  {
    _foos = value;
    SendChange("Foos");
    SendChange("IsThingVisible");
  }
}
public bool IsFoosLoading
{
  ...
  set
  {
    _foosloading = value;
    SendChange("IsFoosLoading");
    SendChange("IsThingVisible");
  }
}
public Visibility IsThingVisible
{
  get { return _foos != null && !_isFoosLoading ? Visibility.Visible : Visibility.Collapsed; }
}

This code manually duplicates exactly what MultiBinding was invented for. In this case, I should use MultiBinding with XAML like this example:

<Button ...>
<Button.Visibility>
  <MulitBinding Converter="{StaticResource MyMultiConverter}"
         ConverterParameter="SomeAndFalse">
    <Binding Path="Foos"/>
    <Binding Path="IsFoosLoading"/>
  </MultiBinding>
</Button>

The logic is now moved into the multi value converter class where it belongs.

if (convertArg == "SomeAndFalse")
{
  bool? flag = values[1] as bool?
  return values[0] != null && flag != true ? Visibility.Visible : Visibility.Collapsed;
}

Note that I didn't just cast values[1] directly to bool, as the value is unpredictably the value UnsetValue. I haven't determined exactly when or why this "try cast" necessary, so I have fallen into the habit of doing it all non-trivial cases to avoid runtime cast crashes.

Summary

Basically everything I've said in this post is a simple restatement of how binding works, but it's a reminder of how important it is to do everything "by the book" and use every binding feature exactly the way it was intended to be used.