Your project’s ‘Getting Started’ tutorial sucks – Why time to success matters

I recently started to learn a new open source JavaScript library. It looked great at first. It had documentation on the library. It had a comprehensive demo. I immediately started through their “Getting Started.” After the first hour, with nothing successful, my excitement began to dim. I’d followed the documentation exactly. I did everything I was supposed to do. And it wasn’t working. After three hours, it still wasn’t working and I started looking for different JavaScript libraries that do the same thing.

How many of you have run across someone’s “Getting Started Tutorial”, felt an initial rush of excitement to learn something new, only to be dismally lost in errors and unclear examples a few hours later?

This isn’t the first time that I have experienced this. I experienced it with C# tutorials for years long before I experienced it with a JavaScript library tutorial. I’ll experience it in whatever language I learn next.

Are you running an op en source project? If so, there is a good chance that your example code sucks.

Why your example code sucks

Well, first off, you are a developer, not a technical writer. There are many little nuances that go into a good piece of technical writing and whether you think so or not, your “Getting Started Tutorial” is technical writing. But you don’t need a technical writing degree to understand why your example tutorial sucks. It is far simpler than that.

You example code sucks for three reasons. The first two are extremely well-known reasons. The third is, for some reason, not obvious or well-known.

  1. You don’t know who your target audience is.
  2. You skip steps you assume are too easy.
  3. You didn’t focus and minimize your tutorial.
  4. *NEW* Your time to success in your tutorial is too long.

Knowing Your target audience

Look, this isn’t hard. If you are an open source project, or just writing a Getting Started tutorial, you need to about your audience. Do you know who they are? For a code tutorial, the audience is almost always the same, with very few exceptions.

Target Audience: Any Developer from one who is just starting out, either in college or in self-learning, to one that has been doing it a few years, to other who have been coding all their lives, and to the old codger who swears at your new modern techniques and bitterly talks of how Cobol is still the best language. Basically, any and all developers.

So now that you know your target audience, you may be confused. Which developer do I write for if I’m supposed to write for all of them?

Well, do you remember in math, when you want to do math with fractions, but they had different denominators. What did you do? You found the lowest common denominator. Yeah, it is the same when dealing with a target audience. You write to the lowest common knowledge level. If you are writing a tutorial or explaining example code assuming an experienced developer only, then your Getting Started tutorial sucks.

Remember the Easy Steps

If you are doing an example in an specific IDE (Visual Studio, Eclipse, etc) and your first step is to create a project in the IDE, but you feel you can leave this step out. So your first step in your tutorial is what to do in the project. You just made your tutorial suck!

What if your user has never used Eclipse and your tutorial is their first experience? How successful are they going to be? The reader is going to be stuck trying to figure out how to even get to step 1.

Don’t skip steps. It doesn’t matter if it is an step-by-step tutorial or a video. If you skip the first step, your started off wrong.

Focus and Minimize Your Tutorial

This is often the worst mistake a tutorial writer can make.

Let’s start off with a bad JavaScript example. You just created a JavaScript library. It is the next best thing. It is going to replace JQuery, Knockout, and Angular. It is the bomb. So naturally your Tutorial for your demo code needs to include other libraries to properly demo your stuff, right? It needs Bootstrap, right? Wrong! If your getting starting example uses any other libraries that is not required for your tutorial, you are failing to minimize. Adding Bootstraps sounds awesome. And there is nothing wrong with a “My Library with BootStrap.js” tutorial. It just shouldn’t be your “Getting Started” tutorial. If you project isn’t Bootstrap or a library that requires bootstrap, leave it out. Minimize.

I recently saw a tutorial on the basics of WCF (Web Services in .NET). The author assumed that the reader already had a project created, an ORM (Entity Framework) installed and referenced, and a database available. Even if this was a more complex tutorial and not a “Getting Started” tutorial, skipping these steps is not good. He was trying to teach how to do something that only related to WCF. An ORM and a database were not necessary. His tutorial limited his audience and had tons of comments from users that were lost, had errors, and couldn’t get his code to work.

Time to Success

Probably the most important factor to a tutorial is time to success. How long does it take your readers to reach success using your project? This is your “Getting Started” tutorials time to success. How long is yours?

If your “Getting Started” tutorial has a time to success of one hour. Your tutorial probably sucks. Why do you think the first thing that every development languages uses as example code is the Hello, Word program? Authors of programming languages long ago inadvertently stumbled onto the fact to time to success matters. Most do it because “Hello, World” is common, not because they understand that time to success is probably the most important factor in their getting started tutorial.

There is not right answer for time to success. The more complex your project, the more dependencies your project has, the more difficult your getting started tutorial will be. However, for a JavaScript library with no dependencies, your time to success should be five minutes or less.

Also, you don’t have to finish your tutorial. You can put multiple success points in your tutorial. Often in coding tutorials, you will see the author tell you to compile and run and see what happens before moving on. This is important, because these compile and run steps are actually there to show that your are succeeding in the tutorial and these steps bring the time to success forward from the end of the tutorial to early on in the process.

Finding out your time to success

The easiest way to find out your time to success is to have a non-developer do it. I recommend you find some one still in High School who isn’t a self-taught coder. Any average high school student will do. My technically writing instructor in college had a daughter in Cheer leading. We had to write a tutorial and they had to successfully follow it. If they couldn’t follow the tutorial in under twenty minutes, we failed. If they could we passed. It was that simple.

An almost perfect example

Would you like an example of a really fast time to success tutorial? I have one for you. It is another JavaScript library. Of the four items above, it does all but skipping steps flawlessly. It has three for four. And the time to success is amazingly short.

In your browser, go here: https://qunitjs.com

Check out QUnit’s Getting Started tutorial. They have an html file and a javascript file. That is it. They know their audience. The example is focussed and minimal. Their time to success is about two minutes.

They do skip steps though. Would a newbie know what that the first step is to create an html file with the html content displayed? No, they wouldn’t. However, QUnit’s project is unique in that it is a library for testing other javascript. So before anyone would hit this library, they are likely already writing web code. See, QUnit knows its audience. And by knowing their audience, they knew (or got lucky) that they are an exception. Because their libraries tests other javascript code, only javascript developers are going to go their page. QUnit will never be the first javascript library a person learns. So they don’t need to cater to the first time newbie. So while, they did break #2 and forget easy steps, they are unique and they get away with it, mostly.

More importantly, their time to success if phenomenal.

Now please, go forth and alter your “Getting Started” tutorial to be equally as awesome.


6 Reasons Why Ad Blocking Is a Short-Term Fad

Recently there has been an influx of people who want to use Ad Blockers. They are great tools, especially when the site is obnoxiously add-filled. Who hasn’t hit a site that had an annoying blinking ad. Or worse, an Ad that suddenly starts music and a loud video. Ugh. Nobody like this.

However, how effective will Ad Blockers be? They will reach peak usage sometime in early 2017 and then almost completely disappear from use by 2020. They will be nothing more than a passing fad.

  1. Ads fund the majority of the internet world
    Content is provided for free if you view the ads. Web site owners have started adding javascript code that refuses to show content if an Ad Blocker is installed. These aren’t just small sites. Very large and popular sites, including Forbes.com, are starting to do refuse to show their content.
    Forbes.com
    This isn’t out-of-the-box simple to do yet (only simple for a skilled JavaScript developer), but it is getting simpler. See #2.
  2. Countering ad blockers will soon be easy and ubiquitous
    WordPress runs 25% of the websites in the world. There are already Ad Blocker detectors plugin, such as the cleverly titled Ad Blocking Detector plugin. It won’t be long until a JavaScript library exists that is easy to use on custom web sites. One might argue that this will start an “arms race” between Ad Networks and Ad Blockers, where each side improves continually. But I see this as a short term Arms race. In this arms race, the money to be made is far greater on the side of the Ad Networks. Such an Arms race will be too costly for Ad Blockers, causing them to either close up shop or stop improving.
  3. Ads can be static or injected server side to appear static
    Ad Blockers won’t block static content. If they do, they will cross a line. Right now Ad blockers are blocking ads based on JavaScript. But what happens when the Ads change to be server side? The content appears static and inline.
  4. Most people don’t even know about block Ads
    So far, the majority of people don’t even know Ad Blockers exists. By the time knowledge of them has spread beyond your average “techie,” their effectiveness will be already countered. Ad Blockers already have a large user base, but compared to the Billions of internet users, their user base really hasn’t penetrated the market.
  5. Most people don’t care enough to install an Ad Blocker
    People are used to ads, and are already used to ignoring them. Some people even like that Google figures out what they like and shows them ads about it.
  6. The Ad Blockers are already no longer blocking all Ads
    The Ad Blockers are now white-listing certain ads. That means that the Ad Blockers are now in the game for money, not for you, because the Ad Blocker is free. So how are Ad Blockers going to make money? By allowing Ads. I know, it sounds crazy. Ad blockers are going to show you Ads to make money. This sounds like a good short term move. The plan is to make their money and get out because soon, by displaying ad, ad blockers are going to alienate their own users.

For all the reasons above, Ad Blockers won’t last long. They will soon lose their effectiveness, and be forgotten. One that happens, after Ad Blocker users get their next phone and next PC/Tablet/Hybrid, users probably won’t even remember to install an Ad Blocker again.

Ad Blockers Will Play an Important Role for Change

However, Ad Blockers will have played an important role. A role for change. So what about Ads are going to change?

  1. Ads Standards will Slightly Improve Ad Quality on Valid Sites
    Advertisers have been able to put out ads unchecked on the internet for almost two decades. Ad networks have risen up. However, the industry as a whole has done a poor job with ad quality.
  2. Ads Will Slightly Improve in Honestly on Valid Sites
    They have also done a poor job with ad honestly. Advertisers have gotten away with ads intended to trick and fool users. Ad blockers are already leading to Ad Networks creating more stringent rules.
  3. Ads Will Be Less Distracting on Valid Sites
    Nobody likes distracting, blinking ads. Some of these are even hard on the eyes. Such ads will no longer exist in the post Ad Blocker world.

Will Ad blockers ever go away?

No. They will always have a niche market, especially among “techies,” some of whom can even write their own ad blockers. But the market will be 1% or less. It might have a small impact and Ad Network’s bottom line, but long term, but not much.

Expect Google To Take Advantage

Google isn’t going to favor sites that use Google Ads over sites that don’t. However, Google could implement a standard of quality for Adsense ads. Then once the majority of ads have complied with those standards, then Google (the search engine) could suddenly include “Ad Quality” as a way to rank sites. Since sites using Adsense will already meet this quality, all sites using Adsense over another Ad network will be ranked higher. Google will profit hugely from this as 3rd party Ad Networks take years to adjust.


How to easily access a web.config AppSettings value with a Type and a default value?

I wanted to make it easier to get a value from AppSettings in the web.config (or the app.config if you aren’t doing web) while converting to the proper type and having a default value.

Here is the syntax I started with that I didn’t like at all.

public static int MaxRetryAttempts = (string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["SmptRetries"]))
    ? int.Parse(ConfigurationManager.AppSettings["SmptRetries"])
    : 3;

I decided I wanted to have the following syntax:

ConfigurationManager.AppSettings.Get<T>(string key, T defaultValue)

I found a blog post that got me started. His syntax was very close to what I wanted already. He didn’t have the default value and he wasn’t an extension method, but wow, was this a real help. I was unaware of TypeDescriptor.GetConverter and was going to basically roll my own with an massively ugly case statement. So I am very happy I found his post.

I created the following NameValueCollectionExtensions.cs file.

using System.Collections.Specialized;
using System.ComponentModel;

namespace Rhyous.Extensions
{
    public static class NameValueCollectionExtensions
    {
        public static T Get<T>(this NameValueCollection collection, string key, T defaultValue)
        {
            var value = collection[key];
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (string.IsNullOrWhiteSpace(value) || !converter.IsValid(value))
            {
                return defaultValue;
            }

            return (T)(converter.ConvertFromInvariantString(value));
        }
    }
}

Details

  1. ConfigurationManager.AppSettings is of Type System.Collections.Specialized.NameValueCollection. So my extension method must be for that type.
  2. I changed the author’s method to be an extension method using the “this” keyword.
  3. I changed from using ConfirationManager.AppSettings to use the first parameter, collection, defined by the “this” keyword.
  4. I added a parameter for a default value.
  5. I changed the method code to return the default value, instead of throwing an exception, if the setting in the web.config is missing or empty.

Usage

I have to retry sending emails. I want the SmtpRetries to be an int obtained from the web.config’s AppSettings and have a default value of 3.

public static int MaxRetryAttempts = ConfigurationManager.AppSettings.Get("SmptRetries", 3);

Unit Tests

I really only wrote unit tests for int conversion. I expect that is sufficient. But if you want to write tests for a double or a other type feel free.

using System;
using System.Collections.Specialized;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Rhyous.Extensions.Tests
{
    [TestClass]
    public class NameValueCollectionExtensionsTests
    {
        private const string Name = "Retries";

        [TestMethod]
        public void IntValueExistsTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            const int value = 3;
            var collection = new NameValueCollection { { Name, value.ToString() } };

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(value, actual, "Valid value should return the valid value.");
        }

        [TestMethod]
        public void IntValueDoesNotExistTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            var collection = new NameValueCollection();

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(defaultMaxRetries, actual, "Missing value returns default.");
        }

        [TestMethod]
        public void IntValueIsEmptyStringTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            var collection = new NameValueCollection { { Name, string.Empty } };

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(defaultMaxRetries, actual, "Empty string returns default.");
        }

        [TestMethod]
        public void IntValueIsWhiteSpaceStringTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            var collection = new NameValueCollection { { Name, "  " } };

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(defaultMaxRetries, actual, "Whitespace string returns default.");
        }

        [TestMethod]
        public void IntValueIsDoubleTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            const double value = 3.5; 
            var collection = new NameValueCollection { { Name, value.ToString() } };

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(defaultMaxRetries, actual, "Invalid value returns default.");
        }

        [TestMethod]
        public void IntValueIsCharsTest()
        {
            // Arrange
            const int defaultMaxRetries = 2;
            const string value = "abc";
            var collection = new NameValueCollection { { Name, value } };

            // Act
            var actual = collection.Get(Name, defaultMaxRetries);

            // Assert
            Assert.AreEqual(defaultMaxRetries, actual, "Invalid value returns default.");
        }
    }
}

Authentication Token Service for WCF Services (Part 6 – A JavaScript client)

Drum roll please . . . This is the moment you’ve all been waiting for. The JavaScript client has finally arrived. In the past articles we have taken control of Authentication in WCF. The token authentication service was designed specifically for ReST like WCF services to be used by modern web and mobile apps. For modern web, that means the Basic Token Service for WCF Services has to work with JavaScript! Of course, it does. That is what it was designed for.

As for the WCF Services, I made a few improvements and fixed some bugs. I am not going to go over those changes. Just know it is a better example than what was delivered in part 6, but not much different.

Download this project here: WCF BTS JS Client

OK. So here is my little html and javascript example. I created a single html file, mostly. I added jquery and knockoutjs from NuGet. The rest is all in the TestPage/Index.html. Really, all you need to know is that there are three buttons. One to test authentication, one to test using the token for calling the test service, and one for using Basic Authentication instead of the token to call the test service.

Here is an image of the page rendered in a browser.

AuthenticationTokenService html and JavaScript

Here is the source code.

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Client</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="/Scripts/jquery-2.1.4.js"></script>
    <script type="text/javascript" src="/Scripts/knockout-3.4.0.debug.js"></script>
    <script type="text/javascript">
        var ViewModel = function () {
            var _vm = this;
            _vm.user = ko.observable();
            _vm.password = ko.observable();
            _vm.basicAuth = ko.computed(function () {
                return "Basic " + btoa(_vm.user() + ":" + _vm.password());
            });
            // I am just sticking the token in a local variable,
            // but you might want to save it in a cookie.
            _vm.token = ko.observable();
            _vm.getResponse = ko.observable();
            _vm.postResponse = ko.observable();
            _vm.onAuthClick = function () {
                $.ajax({
                    method: "POST",
                    url: "/Services/AuthenticationTokenService.svc/Authenticate",
                    contentType: "application/json",
                    context: document.body,
                    data: JSON.stringify({
                        User: _vm.user(),
                        Password: _vm.password()
                    }),
                    success: function (data) {
                        _vm.token(data);
                    },
                    failure: function (err) { alert(err.responseText); },
                    error: function (err) { alert(err.responseText); }
                });
            };
            _vm.onTestGetWithTokenClick = function () {
                $.ajax({
                    url: "/Services/Test1Service.svc/TestGet",
                    contentType: "application/json",
                    context: document.body,
                    beforeSend: function (request) { request.setRequestHeader("Token", _vm.token()); },
                    success: function (data) {
                        _vm.getResponse(data);
                    },
                    failure: function (err) { alert(err.responseText); },
                    error: function (err) { alert(err.responseText); }
                });
            };
            _vm.onTestPostWithBasicAuthClick = function () {
                $.ajax({
                    method: "POST",
                    url: "/Services/Test1Service.svc/TestPost",
                    contentType: "application/json",
                    context: document.body,
                    beforeSend: function (request) { request.setRequestHeader("Authorization", _vm.basicAuth()); },
                    success: function (data) {
                        _vm.postResponse(data);
                    },
                    failure: function (err) { alert(err.responseText); },
                    error: function (err) { alert(err.responseText); }
                });
            };
        };
        $(function () {
            ko.applyBindings(new ViewModel());
        });
    </script>
</head>
<body>
    <div>
        <input type="text" data-bind="value: user" placeholder="Enter your username here . . ." />
        <input type="password" data-bind="value: password" placeholder="Enter your password here . . ." />
        <input type="button" value="Authenticate" data-bind="click: onAuthClick" />
    </div>
    <p>Token: <span data-bind="text: token"></span></p>
    <input type="button" value="Test Get w/ Token" data-bind="click: onTestGetWithTokenClick" />
    <p>Test Get Response: <span data-bind="text: getResponse"></span></p>
    <input type="button" value="Test Post w/ Basic Auth" data-bind="click: onTestPostWithBasicAuthClick" />
    <p>Test Post Response: <span data-bind="text: postResponse"></span></p>
</body>
</html>

Authentication Token Service for WCF Services (Part 5 – Adding SSL)

In the previous article, Basic Token Service for WCF Services (Part 4 – Supporting Basic Authentication), we implemented Basic Authentication. And in the articles before that, our credentials were in the body of the http request. That means we have a huge security issue. Credentials are passing as clear text. This is very, very, very (insert a few thousand more very’s) bad. We need to enabled SSL.

I am going to assume that you know how to do this in production on IIS. I am going to show you how to do this in your development environment.

Download this project here: WCF BTS SSL

Setting Up Visual Studio for SSL

First, let’s get this working in your project. Visual Studio uses needs to launch your project in IIS Express as an SSL site.

  1. In Visual Studio, highlight your project in Solution Explorer.
  2. Press F4 to get the project properties.
  3. Set SSL to true. Notice an SSL url is created on a new port.
ProjectProperties

Setting Up Web Services for SSL

The web.config is where the WCF endpoints are configured. They are currently configured only for HTTP and not HTTPS. So let’s make some web.config edits.

  1. Add an Binding configuration with the security mode set to Transport.
  2. So set the clientCredentialType to none. Remember, we are not using IIS to handle authentication, but instead, we are handling authentication in the service.
  3. use webHttpBinding because We are using JSON and ReST-like (not full ReST) WCF services.
  4. Configure the endpoints to use the newly created Binding configuration.

Here is the complete web.config. The changed or added lines are highlighted.
Changed: Lines 17, 20
Added: Lines 47-55

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfSimpleTokenExample.Services.AuthenticationTokenService" behaviorConfiguration="ServiceBehaviorHttp">
        <endpoint address="" behaviorConfiguration="AjaxEnabledBehavior" binding="webHttpBinding" bindingConfiguration="webBindingSSL" contract="WcfSimpleTokenExample.Services.AuthenticationTokenService" />
      </service>
      <service name="WcfSimpleTokenExample.Services.Test1Service" behaviorConfiguration="ServiceRequiresTokenBehaviorHttp">
        <endpoint address="" behaviorConfiguration="AjaxEnabledBehavior" binding="webHttpBinding" bindingConfiguration="webBindingSSL" contract="WcfSimpleTokenExample.Services.Test1Service" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="AjaxEnabledBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviorHttp">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="ServiceRequiresTokenBehaviorHttp">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <TokenValidationBehaviorExtension />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="TokenValidationBehaviorExtension"
          type="WcfSimpleTokenExample.Behaviors.TokenValidationBehaviorExtension, WcfSimpleTokenExample, Version=1.0.0.0, Culture=neutral"/>
      </behaviorExtensions>
    </extensions>
    <bindings>
      <webHttpBinding>
        <binding name="webBindingSSL">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="BasicTokenDbConnection" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\BasicTokenDatabase.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Configuring the SSL Certificate

An SSL certification was generated for me when I built and ran the project. I was able to choose via a pop-up to trust the certificate.

Go on and check out part 6 here: Basic Token Service for WCF Services (Part 6 – A JavaScript client)


Authentication Token Service for WCF Services (Part 4 – Supporting Basic Authentication)

In Authentication Token Service for WCF Services (Part 3 – Token Validation in IDispatchMessageInspector) we showed how to verify our token against a database. The token is a great tool. The authentication service also provides the token based on a post of credentials.

In this article, we are going to add support for Basic Authentication. We aren’t going to do it the standard WCF way, using Transport security. We will keep our security at none, expect the deployment to be https and roll our own code to handle Basic Authentication.

Download this project here: WCF Basic Auth

There are two features we want in order claim support Basic Authentication.

  1. Allow AuthenticationTokenService.svc to create the token by optionally using Basic Authentication.
  2. Allow Basic Authentication as an option to providing a token.

To provide these two features, first we have to understand Basic Authentication. Basic Authentication is a well-known standard that is defined.

Basic Authentication is an html request header. The header is named “Authorization” and the value is as follows:

Basic amFyZWQ6dGVzdHB3

The first part of the Authorization header value is just the word “Basic” followed by a space.
The second part is the username and password concatenated together with a semicolon separator and then Base64 encoded.

jared:testpw
Basic amFyZWQ6dGVzdHB3

Let’s start with a simple class to manage the Basic authentication header, and encoding and decoding it.

using System;
using System.Text;
using WcfSimpleTokenExample.Model;

namespace WcfSimpleTokenExample.Business
{
    public class BasicAuth
    {
        private readonly string _User;
        private readonly string _Password;
        private const string Prefix = "Basic ";

        #region Constructors
        public BasicAuth(string encodedHeader)
            : this(encodedHeader, Encoding.UTF8)
        {
        }

        public BasicAuth(string encodedHeader, Encoding encoding)
        {
            HeaderValue = encodedHeader;
            var decodedHeader = encodedHeader.StartsWith(Prefix)
                ? encoding.GetString(Convert.FromBase64String(encodedHeader.Substring(Prefix.Length)))
                : encoding.GetString(Convert.FromBase64String(encodedHeader));
            var credArray = decodedHeader.Split(':');
            if (credArray.Length > 0)
                _User = credArray[0];
            if (credArray.Length > 1)
                _Password = credArray[1];
        }

        public BasicAuth(string user, string password)
            : this(user, password, Encoding.UTF8)
        {
        }

        public BasicAuth(string user, string password, Encoding encoding)
        {
            _User = user;
            _Password = password;
            HeaderValue = Prefix + Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", _User, _Password)));
        }
        #endregion

        public Credentials Creds
        {
            get { return _Creds ?? (_Creds = new Credentials { User = _User, Password = _Password }); }
        }
        private Credentials _Creds;

        public string HeaderValue { get; }
    }
}

BasicAuth.cs has constructors that allow for encoding by passing in a username and password and encoding it, as well as constructors that allow for passing in the header value and decoding it to get the username and password.

If we add BasicAuth.cs to our existing WcfSimpleTokenExample project, we can easily use it to support Basic Authentication.

Feature 1 – Basic Authentication for AuthenticationTokenService.svc/Authenticate

By using the BasicAuth.cs class, we can provide support for Basic Authentication in our token service using only 3 lines of code. Below is our new AuthenticationTokenService.svc.cs. Lines 18-20 our the new lines we add.

using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using WcfSimpleTokenExample.Business;
using WcfSimpleTokenExample.Database;
using WcfSimpleTokenExample.Model;

namespace WcfSimpleTokenExample.Services
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AuthenticationTokenService
    {
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        [OperationContract]
        public string Authenticate(Credentials creds)
        {
            if (creds == null && WebOperationContext.Current != null)
            {
                creds = new BasicAuth(WebOperationContext.Current.IncomingRequest.Headers["Authorization"]).Creds;
            }
            using (var dbContext = new BasicTokenDbContext())
            {
                return new DatabaseTokenBuilder(dbContext).Build(creds);
            }
        }
    }
}

Feature 2 – Using Basic Authentication instead of a token

In our TokenValidationInspector.cs file, we are already validating the token using DatabaseTokenValidator, Now we need to validate the crendentials. We can validate credentials using the DatabaseCrendentialsValidator object that is already being used by AuthenticationTokenBuilder. However, we have to add some conditionaly code to test if a token is provided or if Basic Authorization is provided. If both are ignored, the token takes priority.

To do this, I wrapped the existing lines calling DatabaseTokenValidator into a method called ValidateToken. THen I created a new method called ValidateBasicAuthentication, which we only attempt to call a token isn’t provided.

using System.Net;
using System.Security.Authentication;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using WcfSimpleTokenExample.Business;
using WcfSimpleTokenExample.Database;
using WcfSimpleTokenExample.Interfaces;

namespace WcfSimpleTokenExample.Behaviors
{
    public class TokenValidationInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            // Return BadRequest if request is null
            if (WebOperationContext.Current == null) { throw new WebFaultException(HttpStatusCode.BadRequest); }

            // Get Token from header
            var token = WebOperationContext.Current.IncomingRequest.Headers["Token"];
            if (!string.IsNullOrWhiteSpace(token))
            {
                ValidateToken(token);
            }
            else
            {
                ValidateBasicAuthentication();
            }
            return null;
        }
        
        private static void ValidateToken(string token)
        {
            using (var dbContext = new BasicTokenDbContext())
            {
                ITokenValidator validator = new DatabaseTokenValidator(dbContext);
                if (!validator.IsValid(token))
                {
                    throw new WebFaultException(HttpStatusCode.Forbidden);
                }
                // Add User ids to the header so the service has them if needed
                WebOperationContext.Current.IncomingRequest.Headers.Add("User", validator.Token.User.Username);
                WebOperationContext.Current.IncomingRequest.Headers.Add("UserId", validator.Token.User.Id.ToString());
            }
        }


        private static void ValidateBasicAuthentication()
        {
            var authorization = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
            if (string.IsNullOrWhiteSpace(authorization))
            {
                using (var dbContext = new BasicTokenDbContext())
                {
                    var basicAuth = new BasicAuth(authorization);
                    if (!new DatabaseCredentialsValidator(dbContext).IsValid(basicAuth.Creds))
                    {
                        throw new AuthenticationException();
                    }
                }
            }
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }
    }
}

The web.config

There are not changes needed for the web.config. Here is a copy of it though, for reference.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfSimpleTokenExample.Services.AuthenticationTokenService" behaviorConfiguration="ServiceBehaviorHttp">
        <endpoint address="" behaviorConfiguration="AjaxEnabledBehavior" binding="webHttpBinding" contract="WcfSimpleTokenExample.Services.AuthenticationTokenService" />
      </service>
      <service name="WcfSimpleTokenExample.Services.Test1Service" behaviorConfiguration="ServiceRequiresTokenBehaviorHttp">
        <endpoint address="" behaviorConfiguration="AjaxEnabledBehavior" binding="webHttpBinding" contract="WcfSimpleTokenExample.Services.Test1Service" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="AjaxEnabledBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviorHttp">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
        <behavior name="ServiceRequiresTokenBehaviorHttp">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <TokenValidationBehaviorExtension />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add name="TokenValidationBehaviorExtension"
          type="WcfSimpleTokenExample.Behaviors.TokenValidationBehaviorExtension, WcfSimpleTokenExample, Version=1.0.0.0, Culture=neutral"/>
      </behaviorExtensions>
    </extensions>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="BasicTokenDbConnection" connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\BasicTokenDatabase.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Testing Basic Authentication with PostMan

Now we an test that this is working using PostMan. Our PostMan call is similar to what we did in previous articles, but instead of passing a token header, we set Basic Authentication, which sets the Authorization header for us (yes, you could have set the Authorization header manually.)

You could create the Authorization header yourself, but PostMan will create it for you if you click the Authorization and select Basic Auth. Enter your username and password and click update.

PostManBasicAuth

All this does it create an Authorization header for you. You can see this by clicking on the Headers tab in PostMan.

PostManBasicAuthHeader

Go ahead and click Send and you will get your authentication.

Notice the url is https in the image. I haven’t shown you how to do that yet. That is in part 5 here: Authentication Token Service for WCF Services (Part 5 – Adding SSL)


Handling input maxlength using knockout

I set out to handle maxlength with the following goals:

  • Set maxlength on an input field. That took about 10 seconds.

This wasn’t sufficient however. It had two problems:

  1. This prevents the UI from going over the maxlength, but not code. I preferred a solution that did both.
  2. Once the maxlength is reached, there is no indication of why the next character typed is ignored. I wanted the textbox to flash red.

So I decided to do the following:

  1. Have knockout handle the max length and not have maxlength in the html.
  2. Have knockout change the css style for 3 seconds.

Knockout allows for something called extenders. I quickly saw extenders as the way to solve my problem. I followed the documentation and modified the example for my needs. I used Plunker to develop this solution and have a working model here:

http://plnkr.co/edit/9SZzcIPUSwWjBttHDQ64

My extender is as follows:

ko.extenders.maxLength = function (target, maxLength) {
    var result = ko.computed({
        read: target,
        write: function (val) {
            if (maxLength > 0) {
                if (val.length > maxLength) {
                    var limitedVal = val.substring(0, maxLength);
                    if (target() === limitedVal) {
                        target.notifySubscribers();
                    }
                    else {
                        target(limitedVal);
                    }
                    result.css("errorborder");
                    setTimeout(function () { result.css(""); }, 500);
                }
                else { target(val); }
            }
            else { target(val); }
        }
    }).extend({ notify: 'always' });
    result.css = ko.observable();
    result(target());
    return result;
};

Now, as you see, I set the css to errorborder, then I remove it 500 milliseconds (1/2 second) later. In order to make this work, I need an errorborder css style. Here is my first quick stab at that.

.errorborder {
  outline: none;
  border: 2px solid red;
}

.errorborder:focus {
  outline: none;
  border: 2px solid red;
  border-color: red;
  box-shadow: 0 0 3px red;
}

The user will see the border of the text box go red for half a second as they try to type more. Having validation text pop-up saying that maxlength has been reached can be done with this as well, but is probably not necessary. This red border should be sufficient visual feedback.


10 signs you are a Senior Software Developer

Signs of a Senior Software Developer:

  1. Acquires a large foundation of knowledge and continues to learn.
    (Spends as much as 1 hour a day learning more about code. Which is why the Senior dev gets more done. Example: “That project was going to take two weeks. But while studying a came across this open source library that already does that. I solved this problem in an hour by referencing this project and using only a few lines of code.)
  2. Learns what the industry best practices are for a specific project before starting to code.
    (Humble, willing to learn, understands better developers exist.)
  3. Avoids code debt.
    (Frugal with time and code. Understands that debt piles up. Coding it correctly now will, sometime in the future, make a 2-week job take 1 day. Doing it wrong now will, sometime in the future, make a 1-day job take 2 weeks.)
  4. Follows the keep it super simple (KISS) rule.
    (Simplicity is so much more elegant than complexity.)
  5. Follows the 10/100 rule.
    (Code blocks are short. No classes over 100 lines, no methods over 10 lines. You code will natural turn into well-designed code just by following this one principle. You will likely end up using well-known design patterns. If you recognize those design patterns, that is even another sign that you are a senior.)
  6. Uses interface-based design.
    (IoC containers or not, the code is decoupled and uses interfaces, not concrete references that are hard to test.)
  7. Follows the don’t repeat yourself (DRY) principle and recognizes when they do repeat themselves.
    (Writing code takes time. Why would anyone want to write the same code twice?)
  8. Knows what SOLID stands for AND can show an example in actual code of each principle and why it makes sense.
  9. Writes unit tests to test code.
    (Are you still putting your tests in the Program.cs file of a Console Application? You’re not, right? Oh, you are? Seriously?)
  10. Doesn’t outshine coworkers, but instead, makes his coworkers shine, too.
    (When a quarterback wins the Super Bowl, even if named MVP, the rest of the team wins the Super Bowl too. Similarly, when a project is a huge success, you might be the MVP, but everyone in the project participated and contributed to its success, and everyone improved their skills in the process.)

Are you a Senior Software Developer?

My Thoughts

It baffles me that many developers don’t think that acquiring a foundation of knowledge is necessary. In 2010, I read the entire Pro C# 2010 and the .NET 4 Platform: http://www.amazon.com/2010-NET-Platform-Experts-Voice/dp/1430225491. I read it over time. One or two chapters a week and it took less than a year. I did the first 6 chapters really fast. However, I only did a handful of the coding examples. Still, I feel that it made me very knowledgeable in C#. Since then, I always read the “What is new” when a .NET version is released. I’m loving the new multiple level null check feature.

When I started working with WPF, I also watched every single WPF single video available on the now discontinued WindowsClient.net site as well as all the Videos on the Expression Blend site.

I think the key to being a Senior developer is always making the better decisions. Many developers accomplish a task and move on. Some developers design a solution and build upon it. The accomplished task usually is hard to maintain code and everyone wishes it had been done a different way or that it was part of a bigger solution. The designed solution is something that developers can work with, enhance, and improve easily.


Hidden Cyclomatic Complexity due to Parameter Value Coverage

Cyclomatic Complexity

Cyclomatic complexity is the number of branches found in code.

For example:

public int Add(int x, int y)
{
     return x + y;
}

This appears to have a cyclomatic complexity of 1 as there are no branches in your code. One test will give you 100% code coverage.

Detecting Hidden Cyclomatic Complexity

If you have read about Parameter Value Coverage (PVC) you would be aware that some code will do different things without branching in your code. Perhaps the branch occurs in the underlying code. This is still complexity that your code needs to be tested for.

Example 1

Look at the above Add(int x, int y) method. This appears to have a cyclomatic complexity of 1 as there are no branches in this code. One test will provide 100% code coverage if you count coverage by lines.

However, what if your coverage includes different possibilities for the different possible values of your method parameters? What are the possibilities for an int? Well, this example is in C#, so we will assume C# rules. In C#, an int can’t be null. It can be positive, negative or 0. It also has a max value and a minimum value. That is 5 different options that may be involved in Cyclomatic Complexity.

int result = Add(2147483647, 1);

The above code will not result in the answer being 2147483648.

However, the code doesn’t branch if the options are positive, negative, or 0. They code only behaves different if the combination of both values overflow the integer by going above int.MaxValue or below int.MinValue. So the Cyclomatic complexity is 3. It isn’t 1 as most people would assume at first glance.

Example 2

Also look at this simple divide method. This appears to have a cyclomatic complexity of 1 as there are no branches in this code. One test will provide 100% code coverage if you count coverage by lines. However, your code does react differently due to different possibilities for the different possible values of your method parameters.

public int divide(int x, int y)
{
     return x / y;
}

In the above method what happens when either parameter value is 0? Will your code behave the same as if two non-zero values are passed in? Or is there hidden cyclomatic complexity?

Taking into account the hidden cyclomatic complexity, do you still feel this code will never branch? Or do different parameter values cause it to branch? What is the Cylomatic complexity of this method?

If the second value is 0, the code is going to throw a DivideByZeroException. Really, that is the only difference. Since this is divide, it is impossible to overflow the integer, so int.MaxValue and int.MinValue don’t come into play. So the cyclomatic complexity is 2, not 1.

Conclusion

Cyclomatic Complexity is a great tool to measure the complexity of you code. However, failure to test and measure for different possible parameter values can give one a false sense of simplicity and an incorrect Cyclomatic Complexity score.

Branching can occur even in a single line of code. You have been warned!


Html and css for simple banner layout

As many of you know, html and css still hasn’t figured out how to make layout simple and easy. No wonder banners are images. Trying to do a banner that isn’t an image is like beating your head against the wall.

Here is a very basic and very common use case:

  • Banner should not be a full-width image.
  • There is html content on the left that is left justified, html content in the center that is center justified, html content on the right that is right justified.
  • If the screen shrinks, the content in the middle and the right should not wrap.

Failure 1 – The intuitive approach

<div id="frame-banner" style="min-width: 800px">
  <div style="float: left; min-width: 200px">Left Content</div>
  <div style="float: center; min-width: 400px">Middle content</div></div>
  <div style="float: right;min-width: 200px">right content</div>
</div>

Well, even though it seems intuitive to have something float in the center, float: center doesn’t exist, so that just doesn’t work. Would have been cool. I of course, knew float: center didn’t exist.

Left Content
Middle content
Right content

 

Failure 1 – Simple divs

So let’s actually spend some time trying to make this work. Here is what I actually thought should work. Unfortunately, it doesn’t. Some weird formatting happens.

<!DOCTYPE html>
<html>
<head>
<title>html fails at layout</title>
</head>
<body>
<div style="width: 100%;height: 100px;background: gray;margin: 0;padding: 0;">
    <div style="width: 800px;margin: 0 auto;height: 100%;">
        <div style="width: 25%;height: 90%;display: inline-block;background: lightblue;"><div style="background: blue;color: white;margin: 10px;height: 80%;">left<img alt="Image Alt" style="width: 32px; height: 32px;" /></div></div><!-- no space
     --><div style="width: 50%;height: 90%;display: inline-block;background: orange;text-align: center;"><div style="width: 25%;margin: 10px auto;background: blue;color: white;height: 80%;">middle</div></div><!-- no space
     --><div style="width: 25%;height: 90%;display: inline-block;background: lightblue;text-align: right;"><div style="background: blue;color: white;margin: 10px;height: 80%;text-align: right;">right</div></div>
    </div>
</div>
</body>
</html>

I added some hacks to eliminate spacing that shouldn’t exist, but does.

left
middle
right

That looks so good. You think that is going to work right?

Well, let’s add an image and see how that works.

<div style="width: 100%;height: 100px;background: gray;margin: 0;padding: 0;">
    <div style="width: 800px;margin: 0 auto;height: 100%;">
        <div style="width: 25%;height: 90%;display: inline-block;background: lightblue;"><div style="background: blue;color: white;margin: 10px;height: 80%;">left<img alt="Image Alt" style="width: 32px; height: 32px;" /></div></div><!-- no space
     --><div style="width: 50%;height: 90%;display: inline-block;background: orange;text-align: center;"><div style="width: 25%;margin: 10px auto;background: blue;color: white;height: 80%;">middle</div></div><!-- no space
     --><div style="width: 25%;height: 90%;display: inline-block;background: lightblue;text-align: right;"><div style="background: blue;color: white;margin: 10px;height: 80%;text-align: right;">right<img alt="rss" src="http://www.rhyous.com/wp-content/plugins/social-media-widget/images/default/32/rss.png" /></div></div>
    </div>
</div>
left
middle
rightrss

See, as soon as you try to use this layout by adding an image, the layout breaks. Do they do any layout testing in browsers? I’ve heard rumors that the W3C doesn’t believe in supporting layout.

Epic fail. Come on w3C people as well as HTML and CSS developers. There is no excuse for this after twenty years.

Failure 2 – All floats

<!DOCTYPE html>
<html>
<head>
<title>html fails at layout</title>
</head>
<body style="margin: 0; padding: 0;">
<div style="width: 100%;height: 100px;background: gray;margin: 0;padding: 0;">
    <div style="width: 800px;margin: 0 auto;height: 100%;">
        <div style="width: 25%;height: 90%;float: left;background: lightblue;"><div style="background: blue;color: white;margin: 10px;height: 80%;float: left;">left</div></div>
        <div style="width: 50%;height: 90%; background: orange;float:left;"><div style="margin: 10px;height: 80%;"><div style="width: 25%;background: blue;color: white;height: 100%;float: left; position: relative; right: -50%; margin: 0px auto;text-align: center;">middle</div></div></div>
        <div style="width: 25%;height: 90%;float: right;background: lightblue;text-align: right;"><div style="background: blue;color: white;margin: 10px;height: 80%;text-align: right;float:right;">right</div></div>
    </div>
</div>
</body>
</html>

This almost looks right, but wait. How do we actually get it centered? Notice it isn’t centered. It is right of center.

left

right

middle

I can make it left of center, but I have to put the middle after the right and that is a hack:

left
right
middle

But I can’t make it centered. This is not a solution.

Failure 3 – Middle doesn’t float

So what if just the middle element doesn’t float?

<!DOCTYPE html>
<html>
<head>
<title>html fails at layout</title>
</head>
<body style="margin: 0; padding: 0;">
<div style="width: 100%;height: 100px;background: gray;margin: 0;padding: 0;">
    <div style="width: 800px;margin: 0 auto;height: 100%;">
        <div style="width: 25%;height: 90%;float: left;background: lightblue;">
            <div style="background: blue;color: white;margin: 10px;height: 80%;float: left;">left</div>
        </div>
        <div style="width: 50%;height: 90%; background: orange;margin: 0 auto;">
            <div style="margin: 10px;height: 80%;">
                <div style="width: 25%;background: blue;color: white;height: 100%; margin: 0px auto;text-align: center;">middle</div>
            </div>
        </div>
        <div style="width: 25%;height: 90%;float: right;background: lightblue;text-align: right;">
            <div style="background: blue;color: white;margin: 10px;height: 80%;text-align: right;float: right;">right</div>
        </div>
    </div>
</div>
</body>
</html>

That looks horrible.

left

middle

right

Now I have two problems:

  1. The right side is down below my banner.
  2. The top margin of center is applying above the banner, not inside it.

Finally – Success with middle doesn’t float and extra div elements

Well, the final html looks horrible and the center ends up being wrapped in four divs.

To center, you use width: 99%; margin: 0 auto” where the width has to be less than 100%. How is that intuitive. It isn’t. It is horrible. Come on W3C, how hard would it be to add proper intuitive alignment to the html and css spec?

<!DOCTYPE html>
<html>
    <head>
        <title>html fails at layout</title>
    </head>
    <body style="margin: 0; padding: 0;">
        <div style="width: 100%;height: 100px;background: gray;margin: 0;padding: 0px;">
            <div style="width: 800px;margin: 0 auto;height: 100%;">
                <div style="width: 25%;height: 90%;float: left;background: lightblue;">
                    <div style="background: blue;color: white;margin: 10px;height: 80%;float: left;">left</div>
                </div>
                <div style="width: 25%;height: 90%;float: right;background: lightblue;text-align: right;">
                    <div style="background: blue;color: white;margin: 10px;height: 80%;text-align: right;float: right;">Right</div>
                </div>
                <div style="width: 50%;margin: 0 auto;height: 80%; background: orange;padding-top:10px">
                    <div style="text-align:center;width: 90%; margin: 0 auto; background: blue;color: white; height: 80%;">Center</div>
                </div>
            </div>
        </div>
    </body>
</html>

The result is finally acceptable.

left

Right

Center

Let’s add some content to make sure:

Rhyous
top

Follow Us on FacebookFollow Us on Google+Follow Us on TwitterFollow Us on LinkedInFollow Us on RSS
Your Awesome Page Title


cube

Rant on html, css, and W3C

I get that you are trying to do new things with HTML5, but until you actually draw the common layouts, such as two column fixed, three column fixed, and two column liquid, and three column liquid, and actually define the spec to layout properly, it will never work.

Also, without over-wrapping div in div in div, you can’t make html work. That is why all the html and css for the examples on the web look so horrible, because they have to be to work around the terrible job done with html and css layouts.

Layout failures starting with the W3C provided specs are the primary reason why HTML is not the answer for business. I could have written a separate UI for a banner in every platform Android, iOS, Windows, Windows Phone, and Linux, all in less than the time it took me to hack around and figure out what needed to be done in html.


Technology: What tech you use, you want to use for both home and work

I’ve been watching the tablet and smart phone products that have hit the world. They are big money makers. Apple and Google really profited, whereas BlackBerry has nearly died.

I want to discuss the near death of the BlackBerry. Why did the BlackBerry wither while Android and iOS thrived? What is next to wither and what is next to thrive? To answer these questions, let’s look at the PC market in the late 80s and early 90s from many years ago.

Microsoft Windows beat Apple PC

Note: Please forgive this massive short paragraph that is a gross oversimplification.

Apple PCs were all the rage in schools mostly. But Microsoft came out with a new operating system, Windows. It could run on a lot of hardware, and wasn’t stuck on expensive Apple hardware. Businesses started using it over Apple because the hardware was cheaper and the experience was as least as good as that of the Apple PC.

Microsoft and Apple both targeted the business and home users. But Microsoft hit the business faster because their operating could be sold on other manufacturers devices, whereas Apple’s could not. Really quickly, Microsoft Windows took over the business market, and then moved into peoples homes. Windows added solitaire for the home user, which was a very big hit and still is today. In the end, very few people ever brought an Apple PC for their home.

Apple tried to beat Windows and tried to add applications. They even had the market on artistic software for a while but they never have reached the Windows operating system market share.

So Microsoft won by winning both locations, home and work. And once they won, it was hard for Apple to catch up because all the software was written for Windows.

Apple and Google beat BlackBerry

BlackBerry’s main problem was that they didn’t have a device for both consumers and business users. Their phone was pretty much focused on business users. Some might argue that they had consumer models, but even if they did, they didn’t market them well. No one I knew had a personal cell that was a BlackBerry. BlackBerry failed to make the push from business to the home. But that didn’t cause them to wither right away. They needed a competitor.

When the iPhone released, it was a horrible business phone. The first iPhone couldn’t even hook up to Microsoft Exchange, the most popular enterprise and business email server. But the iPhone was a quality smart phone experience, and for non-business features, it had a better user experience than BlackBerry phones. However, many employees ended up having two phones, a personal iPhone and a BlackBerry for work. BlackBerry hadn’t lost yet. In the next two years after the first iPhone version was released, all BlackBerry had to do was up their game to meat the iPhone in features and experience. In essence, the BlackBerry phone needed consumer features and a great user experience. They failed to do that in time. Apple, on the other hand, upped their game and added business features to the iPhone. It could connect to Microsoft Exchange. Users only want one device. So the BlackBerry became obsolete because it didn’t move from the business to the home. The iPhone did move from the home to business.

The only difference from how Microsoft beat Apple in the operating system world and how Apple beat BlackBerry in the business phone world was the third competitor. Google entered the competition and provided an Android phone that gives and experience equal to (or slightly better or worse depending on mostly opinion).

All the apps were written for both iPhone or Android.

Google, however, was a little late to the game. Had they released their phone even a year earlier, I think Apple would have lost and history would have repeated itself. Remember, why Apple lost the PC market? It required expensive proprietary hardware. Well, so does the iPhone. Google took the place of Microsoft in providing an operating system that could install on any platform. And any vendor could sell their own operating system with Android. Google’s Android exploded into the world and is the most used operating system on phones by a large margin.

The big difference between the smart phone market and the PC market of the late 80s and 90s is that Apple already had the applications, now calls apps, already written for the iPhone. So when Google’s Android won the majority market share, Apple didn’t lose everyone. They maintain a very good market share of phones and each release is a hit.

Both phones are quite acceptable for business or work.

However, the Microsoft Phone was very late to the game. It would be great for business and home, but it doesn’t have the apps. They are already written for iPhone and Android phones. BlackBerry and Microsoft both lost.

What about the Tablet market?

So who is going to win it? Some might say the iPad has already won. Well, let’s look at what tablet today works for both home and business users? Is their one yet? Or is it in the same position that BlackBerry was in, only reversed?

The iPad is a great consumer device. But input is atrocious. Running a project in a meeting with requires a bunch of special connectors or wi-fi enabled connectors. It just doesn’t do it for the business user. Many people bought their iPads with hopes to use them at home and at work. But really, they are just home devices. Many employees that used to bring them to work are now leaving them home and have gone back to their laptops.

The Android tablets are pretty much the same experience. Input is just as terrible. I gave up on the keyboard I bought for it. Android tablets have all the same problems in a business environment that the iPad has. However, Android has one advantage over the iPad in that Android can be installed on other hardware, while iOS cannot.

Now, enter the Microsoft Surface and Surface Pro. Since version 3 released, it’s business usability is unquestionable. It is the same operating system that has been running businesses for a quarter of a century. The home experience is not quite as good as the iPad or Android, but it is acceptable and getting better. In fact, I just watched a few hours of Amazon prime on it instead of on my Kindle Fire HD and had a better experience.

The Surface Pro is here and is already at version 3 with Version 4 coming around the bend. It works for home and business. Also, Windows can install to other devices and other manufacturers such as Lenovo are releasing devices similar to the Surface Pro, also running Microsoft Windows.

Can Apple and Google catch up? Can they get the business market and the home market? I don’t see how.

I have already seen the Surface Pro 3 turn iPads into paper weights, well actually kid’s toys as parents stop using them and let their kids game on them. (That is what has happened to my Kindles.)

Conclusion

History shows that while there is money in an either consumer-only or business-only solution, if the solution is needed by both, the winner is whoever fills the needs of both.

If history repeats itself, and I think it will, Microsoft is going to win the Tablet operating system market simply by making the existing desktop and laptop operating system their tablet operating system. It makes the tablet usable for both home and work. The only question is, how much a market share will Apple and Android tablets keep?

There over a billion laptops in the world and most people want them to be thinner and lighter, though not necessarily smaller in screen size. I was quite surprised, however, that even though I was a 16″ or 17″ inch laptop screen guy, that I was willing to trade-off screen size for the light weight, slim Surface Pro 3.

So yes, the first tablet that is very usable for both home use and business use is the Windows Tablet. This is history repeating themselves. All the other tablets are like the early Apple PC, or the BlackBerry. There are once again differences to the current situation.  Apple and Android own the smart phone markets and those smartphone apps run on tablets too, so Apple will never really loose in the apps department. Microsoft’s tablet has already won in the application (full desktop application) market and so while it doesn’t have the apps, that doesn’t matter anymore, it has the applications. The apps will come because the Surface and similar devices are selling very well and will quickly take over the market share.

By the way, as developers write apps for the Surface (not applications), those apps will work on the Windows phone and Windows might just make a comeback in that arena thanks to winning the tablet market. Oh, and you may not think you will every run a windows phone, but what if your desktop/laptop/tablet is nothing more than a windows phone? What happens in a few years when your phone becomes your only device? Which operating system would you choose in a single device world? Most would say Windows (though there will always be Mac and BSD/Linux users). You get to work and dock your windows phone and it is as powerful as your most powerful desktop today and runs your dual monitors at your desk? It streams wirelessless to dumb screens, which were once tablets, but now just run off your phone.

Welcome back to the top Microsoft. Some might even say you never left.

And thank you for building the Surface Pro 3. I love mine. It is replacing my desktop and laptop.


Simpler inheritance in Javascript

I’ve been working more in JavaScript and decided I need some inheritance. I had a couple of classes that need to inherit the properties and methods of a base class. I’ve learned inheritance methods in javascript. The prototype inheritance just never really felt right.

Well, today it just dawned on me that I might not so much want inheritance as I want one place to implement my fields and methods. The prototypal inheritance method doesn’t exactly work for what I want. I don’t want to add methods to the prototype.

See this project fully unit tested with qunit here: Simpler Javascript Inheritance

The inheritance template

To make this method of JavaScript inheritance work, all you have to do is define an objects members using a method. I will use an init method.

// The template
var TemplateBaseClass = function(child) {
  var _self = this;
  _self.init = function(obj) {
    // define all members here using obj.member syntax.
  };
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
};

With this template we can now implement inheritance with far more simplicity than the prototypal method.

Example base class and inheritance

Let’s look at an example BaseClass that uses the Inheritance template

// Non-abstract base class
// You can use new BaseClass() or any child. 
var BaseClass = function(child) {
  var _self = this;
  _self.init = function(obj) {
    obj.field1 = null;
    obj.field2 = null;
    obj.action1 = function() {
      return true;
    };
    obj.action2 = function() {
      return true;
    };
  };
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
};

The above BaseClass creates a few fields and methods. It uses the template we’ve created. It allows inheritance. Let’s inherit from it. Check out this ChildClass below.

// A child of BaseClass
var ChildClass = function(child) {
  var _self = this;
  var _base = new BaseClass(_self);
  _self.init = function(obj) {

    // Overriding a base method
    obj.action1 = function() {
      return _base.action1() && _self.truefalse; // can call base.action1()
    };

    // Child class fields and methods
    obj.field5 = null;
    obj.truefalse = false;
    obj.action5 = function() {
      return true;
    };

    // expose base class
    obj.getBase = function() {
      return _base;
    }
  }
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
}

As you see, ChildClass inherits BaseClass(). They have all the same field and method signatures. Methods can be defined in the base class and don’t have to be redefined. Also notice that we didn’t have to mess with the clunky object.prototype or object.Create() syntax.

Note: Well, this is sort of inheritance. BaseClass and ChildClass actually have completely separate instances of the fields and methods. We can fix this for methods (I’ll show you later) but we can’t really fix this for members. Still, that limitation doesn’t really cause any immediate problems.

Example abstract base class and inheritance

Well since we don’t really need the base class to actually have the fields and methods, let’s implement it so it doesn’t. Notice that we don’t call _self.init(_self).

// Abstract base class (like an Interfaces but with the implementation)
// While you can call new AbstractBaseClass(), it doesn't have any
// of its members.
var AbstractBaseClass = function(child) {
  var _self = this;
  _self.init = function(obj) {
    obj.field3 = null;
    obj.field4 = null;
    obj.action3 = function() {
      return true;
    };
    obj.action4 = function() {
      return true;
    };
  };
  if (child)
    _self.init(child); // only instantiates fields and method to child
};

This is pretty identical to the code above, only the base class doesn’t implement any of the fields or methods it defines. I like to think of this as an Abstract class, or an interface that also includes implementation.

Let’s inherit from AbstractBaseClass.

// A child of the AbstractBaseClass
var ChildOfAbstractClass = function(child) {
  var _self = this;
  AbstractBaseClass(_self); // not saving AbstractBaseClass as it can't be used

  _self.init = function(obj) {
    // Overriding a base method
    obj.action1 = function() {
      // cannot call base.action1() because it doesn't exist
      return obj.truefalse;
    };

    // Child class fields and methods
    obj.field6 = null;
    obj.truefalse = false;
    obj.action6 = function() {
      return true;
    };
  }
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
}

As you see, inheriting from an abstract class is the same with the exception that you cannot call any base members or methods as the base object doesn’t have them.

Implementation where base class and child class share fields and methods

Well, to share a method, the syntax is simple. Here is our original BaseClass from above, changed so methods in a child are the same as the method in the base class.

// Non-abstract base class
// You can use new BaseClass() or any child. 
var BaseClass = function(child) {
  var _self = this;
  _self.init = function(obj) {
    obj.field1 = null;
    obj.field2 = null;
    obj.action1 = _self.action1 || function() {
      return true;
    };
    obj.action2 = _self.action1 || function() {
      return true;
    };
  };
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
};

How simple was that. We just assign the object _self.action1 if it exists, if not we assign it a new function. This works because both the base class and child class have a reference to the same method. However, with fields, this wont’ work because the calling _self.field1 would return a value of null, not a reference. They will have the same value initially, but changing the value in the child class won’t change the value in the base class.

One nice way to fix this is to implement the Property object. This is nice as it is basically a wrapper around the ubiquitous get/set methods familiar to all languages. Here is a simple implementation of a Property.

// A property class 
var Property = function() {
  var _self = this;
  var _backingField = null;
  _self.get = function() {
    return _backingField;
  }
  _self.set = function(value) {
    _backingField = value;
  }
}

Now let’s implement a base class using Properties instead of fields.

var BaseClassWithProperties = function(child) {
  var _self = this;
  _self.init = function(obj) {
    obj.prop1 = _self.prop1 || new Property();
    obj.prop2 = _self.prop1 || new Property();
  };
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
};

As you see, instead of assigning the fields a null value, we assign them a new object. Notice we can use our syntax, _self.prop1 || new Property();, to make sure that the base class and the child class share the same get/set Property.

Let’s implement a child class that also uses properties.

// A child of the BaseClassWithProperties 
var ChildProperties = function(child) {
  var _self = this;
  var _base = new BaseClassWithProperties(_self); // not saving AbstractBaseClass as it can't be used

  _self.init = function(obj) {
    // Child class properties
    obj.prop3 = new Property();

    // expose base class
    obj.getBase = function() {
      return _base;
    }
  }
  _self.init(_self); // instantiates fields and method to itself
  if (child)
    _self.init(child); // instantiates fields and method to child
}

Now if I create a new ChildProperties object and call it’s setter, the value is set for both the parent and the child object.

A sealed class

The idea of a sealed class is one that can’t be inherited from. Simply don’t implement the template and you have a sealed class.

// A child of the BaseClassWithProperties 
// since it doesn't implement the child parameter and the init function, it is sealed and not usable for inheritance.
var SealedClass = function() {
  var _self = this;
  var _base = new BaseClassWithProperties(_self); 
  
  // Child class properties
  _self.prop3 = new Property();

  // expose base class
  _self.getBase = function() {
    return _base;
  }
}

I want many child class that inherit the same


Why we need RFCs for database implementations!

We eschew reinventing the wheel in every aspect of development, yet when it comes to creating a customer database, or an order database, everyone creates their own. They roll out their own database model, usually to their regret, and have to roll their own create, read, update, delete (CRUD) services. We’ve been using databases for decades and somehow, we have failed to eliminate the constant repetition of the same work. Everyday someone is creating a Customer or Order database model from scratch. Why?

We have technologies like Entity Framework, NHibernate, Linq to Sql, etc… to help try to make sure we don’t reinvent the wheel for Object-relational mapping (ORM, a technique to talk to a relational database with object-oriented code), but we are constantly doing it just above the ORM layer because we are reinventing the database itself. Look at the design below. The blocks in red are the ones we are reinventing over and over again.

Reinventing the database wheel

Red = Layers in which we reinvent the wheel and duplicate a lot of code

Let’s look at how this causes a chain reaction of reinventing the wheel. No only do we reinvent the wheel for the services, we do so for the UI. You can break it down further from UI to MVC or MVVM, or your favorite UI partern, and you will see that we are duplicating a lot of code that we just don’t need to duplicate.

This also has an effect on Business Intelligence (BI). Because everyone is created a completely different database design, all the queries to get data from the database are different. These queries are used to build reports or to mine the data into a a data warehouse. The data often has to go through an Extract, Translate, Load (ETL) procedure to even make it reportable. Why?

Reinventing the database wheel chain reaction

Why are we all excepting the need to reinvent the wheel in so many layers? Is the open source world missing the vision of separation of concerns? We have entire projects that are tightly coupled end to end, some are far better and are loosely coupled end to end. But we don’t have a well-tuned engine of replaceable parts.

Why is it that we don’t have a place for a common database schema and ORM design. The closest thing I have found is this:
http://www.databaseanswers.org/data_models

This list of common schemas is really great, but it is just one box of the image above and that box isn’t even complete. We need not only common data models, but we need them in a source control repository so people can branch them, change them and contribute back. We need versions for MS Sql, Oracle, MySql, Postgresql, etc… We need tests to make sure the data models scale. We need a common services layer, and not just in one language. Perhaps Java, C#, and PHP to start out with, so companies don’t have to change the language they code in to use this.

Imagine it. Software startups could really get a jumpstart if they could download a schema in the database they want to use (perhaps Postgresql), a common service layer in their language (perhaps C#), and then build their proprietary idea on top of that. The startup can claim to implement the standard data model (SDM) and so enterprise companies can know their software will drop in.

UI designers could start building purchasable UIs for these database models and services.

BI companies could start selling prepackaged content reports along with their BI software.

This blows up even bigger when you start stacking these up. We could start using either inheritance or data model bundling. A shopping cart database model be combination of a person database model an order data model, and a Product data model. A software product data model might inherit from Product data model and add a few software specific tables, etc… When a full solution is released, each bundled model is independent of the rest. Each could be on their own databases instances on different servers if desired.

Now you can see how integration becomes so much easier. You start seeing how two completely separate applications could share the same data source. No more ETL from one system to the next for integration purposes. You wouldn’t need to do that. Imagine you have already implement your Customer Relationship Management (CRM) using Standard Data Models (SDMs), and then you want to implement an E-Commerce shopping cart. They choose an E-Commerce shopping cart that also uses the SDMs. Instead of having to migrate customers into the E-Commerce solution, they simply redirect the E-Commerce solution’s customer data model to point to their existing system. The rest of the E-Commerce data models can point to a separate database.

I feel like everyone is missing the big picture here. What do you think?


How to populate MailTo link with a form action using Javascript

Someday you might want to have a form where the submit button goes to a MailTo: link. You might want to populate the email’s To: Subject: and Body.

Here is a plunk to do it:
http://plnkr.co/edit/HWkMHhlaN5MO82wQfa0q

Here is the html and javascript:

<html>
<head>
<script>
function sendemail()
{
    var body = "First name: " + document.getElementById("fn").value + "\n";
    body +=  "Last name: " + document.getElementById("ln").value;
    var email = document.getElementById("email").value;
    var location = "mailto:" + email + "?subject=Hello world&body=" + encodeURIComponent(body);
    window.location.href = location;
}
</script>
</head>
<body>
<form action="javascript: sendemail()">
First name:<br>
<input id="fn" type="text" name="firstname">
<br>
Last name:<br>
<input id="ln" type="text" name="lastname">
<br>
Email:<br>
<input id="email" type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>

How to get and set private fields or properties in C#

Sometimes you want to access a private member of an object. If you were the author of such object, you would simply change the encapsulation from private to public, or protected if you just want access from a child. However, what if you don’t have access to the object. What if it is one of the standard .NET library objects. You can’t change it. What are your options?

  1. Rewrite the entire class. (Not easy and I don’t recommend it)
  2. Recreate the value somehow (which might not even be possible)

Well, guess what. Microsoft left a nice workaround to encapsulation in its implementation of Reflection.

Here is a nice class you can use to get the value of any private member.

using System;
using System.Linq;
using System.Reflection;

namespace Rhyous.TextBlock.Business
{
    public class PrivateValueAccessor
    {
        public static BindingFlags Flags = BindingFlags.Instance
                                           | BindingFlags.GetProperty
                                           | BindingFlags.SetProperty
                                           | BindingFlags.GetField
                                           | BindingFlags.SetField
                                           | BindingFlags.NonPublic;

        /// <summary>
        /// A static method to get the PropertyInfo of a private property of any object.
        /// </summary>
        /// <param name="type">The Type that has the private property</param>
        /// <param name="propertyName">The name of the private property</param>
        /// <returns>PropertyInfo object. It has the property name and a useful GetValue() method.</returns>
        public static PropertyInfo GetPrivatePropertyInfo(Type type, string propertyName)
        {
            var props = type.GetProperties(Flags);
            return props.FirstOrDefault(propInfo => propInfo.Name == propertyName);
        }

        /// <summary>
        /// A static method to get the value of a private property of any object.
        /// </summary>
        /// <param name="type">The Type that has the private property</param>
        /// <param name="propertyName">The name of the private property</param>
        /// <param name="o">The instance from which to read the private value.</param>
        /// <returns>The value of the property boxed as an object.</returns>
        public static object GetPrivatePropertyValue(Type type, string propertyName, object o)
        {
            return GetPrivatePropertyInfo(type, propertyName).GetValue(o);
        }

        /// <summary>
        /// A static method to get the FieldInfo of a private field of any object.
        /// </summary>
        /// <param name="type">The Type that has the private field</param>
        /// <param name="fieldName">The name of the private field</param>
        /// <returns>FieldInfo object. It has the field name and a useful GetValue() method.</returns>
        public static FieldInfo GetPrivateFieldInfo(Type type, string fieldName)
        {
            var fields = type.GetFields(Flags);
            return fields.FirstOrDefault(feildInfo => feildInfo.Name == fieldName);
        }

        /// <summary>
        /// A static method to get the FieldInfo of a private field of any object.
        /// </summary>
        /// <param name="type">The Type that has the private field</param>
        /// <param name="fieldName">The name of the private field</param>
        /// <param name="o">The instance from which to read the private value.</param>
        /// <returns>The value of the property boxed as an object.</returns>
        public static object GetPrivateFieldValue(Type type, string fieldName, object o)
        {
            return GetPrivateFieldInfo(type, fieldName).GetValue(o);
        }
    }
}

And here is how to use it.

Imagine you have a class with a private Field and a private property.

public class A
{
    private int MyPrivateProperty
    {
        get { return _MyPrivateField; }
        set { _MyPrivateField = value; }
    } private int _MyPrivateField = 27;
}

You can access the value as follows:

    var a = new A();
    // Get values
    int privateFieldValue = (int)PrivateValueAccessor.GetPrivateFieldValue(typeof(A), "_MyPrivateField", a);
    int privatePropValue = (int)PrivateValueAccessor.GetPrivatePropertyValue(typeof(A), "MyPrivateProperty", a);

    // Set Values
    PrivateValueAccessor.GetPrivateFieldInfo(typeof(A), "_MyPrivateField").SetValue(a, 11);
    PrivateValueAccessor.GetPrivatePropertyInfo(typeof(A), "MyPrivateProperty").SetValue(a, 7);

Access private fields or properties from a base class

OK, so now that we have this class, you can imagine that you can now use it in a child, if you have no other choice, in order to expose A.MyPrivateProp.

public class B : A
{
    public int ExposedProperty
    {
        get { return (int)PrivateValueAccessor.GetPrivateFieldValue(typeof(A), "_MyPrivateField", this); }
        set { PrivateValueAccessor.GetPrivateFieldInfo(typeof(A), "_MyPrivateField").SetValue(this, value); }
    }
}

Now you have exposed the private value in your child class. You can call it as normal.

            var b = new B();
            b.ExposedProperty = 20;

Here is what it looks like in the debugger before you set it.

b    {B}    B
    base    {B}    A {B}
        _MyPrivateField      27    int
        MyPrivateProperty    27    int
        ExposedProperty      27    int
        b.ExposedProperty    27    int

And after setting B.ExposedProperty to 20, it looks like this.

b    {B}    B
    base    {B}    A {B}
        _MyPrivateField      20    int
        MyPrivateProperty    20    int
        ExposedProperty      20    int
        b.ExposedProperty    20    int

Conclusion

You now have a serviceable workaround for a getting and setting a private field or property.

It really isn’t going to perform well, since it uses Reflection, but if it is a single value that you only set once, you won’t have a performance problem.

Since it is so easy to break encapsulation with Reflection, it makes me wonder what the point of encapsulation is in C#? But it still has it’s purposes, I know.