Ocean Validation for Xamarin Forms

Introduction

This blog post is about an example Xamarin Forms project I wrote to show using Prism, Unity, and Ocean Validation in several scenarios.

I decided to make this a video blog post and have six videos for you.

You learn the following:

  • Using the sample Xamarin Forms app and understanding the line of business scenarios it covers.
  • Using Prism and Unity in a real-world Xamarin Forms App
  • Dependency injection in a real-world Xamarin Forms App
  • Abstracting Static services and Static Device information behind interfaces to promote testing and maintainable code
  • Using Prism NavigationService and PageDialogService
  • Async Await contrasted with the Promise pattern in a Xamarin Forms App
  • Ocean validation framework with Xamarin Forms
  • Using IDataErrorInfo to surface validation errors for properties or the entire object.  (Yes, IDataErrorInfo!)  This also works for UWP.  These two platform’s binding pipeline lack data validation.  No worries, it’s very easy to do now.
  • Using Ocean validation to validate an object in multiple states.  Multiple validation states imply that the object is going through a workflow, where an object can be valid for a certain state, but not valid for other states.  This is a common scenario in complex business applications like insurance claims or when an object is completed over several Xamarin Forms pages.
  • At the end of November 2016, the Xamarin Forms ListView view began to have some problems that cost me over a day.  In the last video, I explain the issues and what I did to get around them.  I also wrote up bugs and communicated with Microsoft about these issues.

Introduction to Ocean for Xamarin Forms

Prism and Dependency Injection in Ocean for Xamarin Forms

Async Await and Promise Pattern in Ocean for Xamarin Forms

Introduction to Ocean Validation Framework for Xamarin Forms

Ocean Multi-Object State Validation for Xamarin Forms

Xamarin Forms ListView Troubles (as of 1 Dec 2016)

Source Code

https://github.com/Oceanware/OceanForXamarinForms

Close

I hope these videos have helped with your understanding of Prism, Unity, and Ocean in Xamarin Forms.

Have a great day,

Just a grain of sand on the world’s beaches

Updated Xamarin Forms BindablePicker

Introduction

On 9/30/2016 I updated the Xamarin Forms Bindable Picker, correcting it to handle the view model clearing the Items ObservableCollection.

When the view model exposes an ObservableCollection as the BindablePickers ItemsSource and the view model clears that collection, the BindablePicker now responds correctly and updates the UI as expected by:

  • Removing all items in its collection
  • Setting SelectedItem to null
  • Setting SelectedValue to null
  • Setting SelectedIndex to -1

Much appreciate the feedback and bug reports I’ve received to make this control much better.

Close

Have a great day,

Just a grain of sand on the world’s beaches

AngularJS 1.5 Input Components

Introduction

The promise of JavaScript component-based architecture frameworks such as AngularJS 1.5, Angular 2, or Aurelia is enabling developers to write less code, both HTML markup, and JavaScript.  The ability to encapsulate HTML and JavaScript into reusable components should simplify the application consuming these components greatly.

Please, review this post and code, and then start your own component library for your applications. There are enough components here to get you started.  I have chosen to make these components granular with a single responsibility, rather that make a single component with many properties to change the behavior. This approach provides clean and readable HTML markup, clearly describing the components role and behavior.

This blog post and GitHub repo are written using ES6. I wrote why I use ES6 JavaScript here. I also leverage ES7 experimental class property features in my applications.

AngularJS 1.5 components are uncomplicated element directives. These components can encapsulate business logic and are testable.

If you have time, compare the amount of JavaScript code is required by Angular 2 components to the AngularJS 1.5 components. You’ll find that AngularJS 1.5 is simpler and currently requires considerably less framework code to register. You’ll also see that I separate the component registration from the component, this removes Angular from the component enabling very fast executing unit tests.  See the Review Presentation repo example.

The below images show the clean and minimal HTML required to produce a typical data form with comprehensive validation and associated messages, including password strength metrics. The “match” directive (see app.module.js) on the second input-password component handles comparing the two passwords. The corresponding error message is displayed below these components. The input control placeholder is included for instructional purposes only and is probably not needed in a simple form like this one.

html

form

References

I did my research before embarking on creating these input components. I’m very grateful to the many community authors for their blog posts and answers on StackOverflow. The below links helped me to understand this problem space and I recommend that you study them:

Creating a custom form field with validation using AngularJS 1.5 and TypeScript

Password Strength Meter

InputBaseComponent

The InputBaseComponent is the base class for the text input components. It exposes properties common to all HTML text input controls.

The InputBaseComponent creates the component label from the name attribute if the label attribute is not supplied. It’s onInit, onChange, and validate methods are invoked by deriving classes.

Normally an AngularJS 1.5 component does not update it’s parent model directly. As explained in the above blog post this component design calls for updating the model instead of using two-way bindings or a one-way binding with a corresponding event.

I agree with this architecture in this specific use case because it mimics the interaction that an input control would have if it was not encapsulated in a separate component. It is assumed that the form these components are hosted on would be adhering to the typical AngularJS component design pattern described in the AngularJS documentation.

By requiring the model in the component registration (see input-components.module.js), the model will be injected and is available to the component controller for reading and writing. When the view needs to be updated, $render is invoked and the below function updates the component value. When the component value is changed, the model value is set in the onChanage method.

COMPONENT REGISTRATION: 
require: {
    model: "ngModel"
}

ONINIT:
this.model.$render = () => {
  this.value = this.model.$viewValue;
}

ONCHANGE:
this.model.$setViewValue(this.value);

This base class handles setting sane values for the maximumLength and for setting  isRequired based on the minimumLength. The isRequired property is used in the HTML to set a required attribute.

The onChange method provides data input length validation by limiting the value length to the maximumLength.  This code is wrapped in try-catch block to provide a seam for logging an obvious attempt to hack your site. Remember, always defend in layers and never trust any data from the internet either on the client or server.

The validate method checks the input for minimum or maximum length validation rule violations. What is nice about this implementation is that the validation messages can easily be customized to provide the user with good information.  In this application, I’ve chosen to display the validation message next to the label.  If you don’t do this, then be sure to include the label in your validation message.

export default class InputBaseComponent {

  label;
  model;
  value;
  name;
  validationError;
  minimumLength;
  maximumLength;
  isRequired = false;

  constructor(StringUtility) {
    this.StringUtility = StringUtility;
    if(this.name && !this.label) {
      this.label = this.StringUtility.parseWords(this.name);
    }
  }

  onInit() {
    this.model.$render = () => {
      this.value = this.model.$viewValue;
    }
    if(!this.maximumLength) {
      this.maximumLength = 200;
    }
    if(this.minimumLength) {
      this.isRequired = true;
    }
  }

  onChange() {
    try {
      if(this.value && this.maximumLength && 
          this.value.length > this.maximumLength) {
        this.value = this.value.substring(0, this.maximumLength);
      }
    } catch(e) {
      this.value = '';
      // log this to your system as a security message
    }
    this.model.$setViewValue(this.value);
  }

  validate() {
    if(this.isRequired && this.minimumLength) {
      if(!this.value || this.value.length < this.minimumLength) {
        this.validationError = `has a minium length of ${this.minimumLength}`;
        return false;
      }
    }
    if(this.value && this.maximumLength && 
        this.value.length > this.maximumLength) {
      this.validationError = `has a maximum length of ${this.maximumLength}`;
      // log this to your system as a security message
      return false;
    }

    this.validationError = '';
    return true;
  }

}

InputBaseComponent.$inject = ['StringUtility'];

InputTextComponent

Now that we have all the hard work done, let’s extend InputBase and call the required methods.  For an input of type text, no additional validation is required.

import InputBase from '../input-base'

export default class InputTextComponent extends InputBase {

  constructor(StringUtility) {
    super(StringUtility);
  }

  $onInit() {
    super.onInit();
    super.validate();
  }

  onChange() {
    super.onChange();
    super.validate();
  }
}

InputTextComponent.$inject = ['StringUtility'];

InputEmailComponent

The InputEmailComponent extends the InputBase and adds email input validation. Notice that if the call to super validate returns false, this validation does not run.  You can change this logic to display all validation errors or display them one at a time as I do.

import InputBase from '../input-base'

export default class InputEmailComponent extends InputBase {

  constructor(StringUtility) {
    super(StringUtility);
  }

  $onInit() {
    super.onInit();
    this.validate();
  }

  onChange() {
    super.onChange();
    this.validate();
  }

  validate(){
    if(super.validate()) {
      if(this.value && 
          !this.StringUtility.isEmailValid(this.value)) {
        this.validationError = ' has invalid format';
        return;
      }
    }
  }
}

InputEmailComponent.$inject = ['StringUtility'];

InputTextComponent Template

This template has four groups:

  • input-group – apply CSS styles for spacing and alignment
  • form – subform container for the component
  • label-area – displays the label and associated validation messages
  • input – the input control

The validation messages are shown when:

  • the form control is invalid
  • and validation error text has a value
  • and
    • the control has been touched
    • or parent form has been submitted

You can choose when users see validation messages. I’ve used the above logic in my applications and users are happy with the experience.

<input-group>
  <ng-form name="{{vm.name}}Form">
    <label-area>
      <label for="{{vm.name}}">{{vm.label}}</label>
      <error-message ng-show="{{vm.name}}Form.{{vm.name}}.$invalid && 
        vm.validationError && 
        ({{vm.name}}Form.{{vm.name}}.$touched || 
        {{vm.name}}Form.$$parentForm.$submitted)">
          {{vm.validationError}}</error-message>
    </label-area>
    <input
      type="text"
      placeholder="{{vm.label | lowercase}}"
      autocomplete="off"
      ng-model-options="{allowInvalid: true, debounce: 250}"
      name="{{vm.name}}"
      id="{{vm.name}}"
      ng-model="vm.value"
      ng-change="vm.onChange()"
      ng-required="vm.isRequired"
      ng-minlength="vm.minimumLength"
      ng-maxlength="vm.maximumLength"
      maxlength="{{vm.maximumLength}}"
      >
    </input>
  </ng-form>
</input-group>

HTML Input Control

  • placeholder – optional.  I like, that I can bind the label and then use an Angular filter to change the label to lower case.
  • autocomplete – choose the option that meets your requirements
  • ng-model-options
    • allowInvalid – when true, allow ng-change to be raised on keystrokes when the control is invalid.
    • debounce – the time delay for model updating since the last keyboard input.
  • ng-model – binds to the component value
  • ng-change invokes the onChange method
  • ng-required – when true, sets the required attribute on the control
  • ng-minlength – sets the minimum length rule for the control
  • ng-maxlength – sets the maximum length rule for the control
  • maxlength – I STRONGLY urge you to ALWAYS set this attribute on any text input control.  Setting this attribute limits the number of characters that can be entered, pasted or dragged into the control at runtime. Remember that security is always in layers.

Form Submit Button Options

There are two schools of thought around form submit buttons.  One is to disable the submit button when the form is invalid, the other to allow the user to click the submit button and then show all input validation messages.

Your choice will depend on the application requirements and stakeholder choices.

The submit button strategy needs to take into account the applications timing of when to render validation messages.

I prefer to only show validation messages after the user visits the control or when the user submits the form and the control is invalid.

Thoughts

Whether you’re using AngularJS 1.5, Angular 2, Aurelia, et al., components provide the HTML and JavaScript developer a powerful programming paradigm that embraces separation of concerns, test ability, maintainability, readability, and are down right fun to work with.

Download

https://github.com/Oceanware/InputComponents

Close

Have a great day,

Just a grain of sand on the world’s beaches

.NET Unit Testing Tools

Introduction

There are no silver bullets in our chosen profession, software engineer. Select tools and technologies that meet your requirements. When adopting tools, be prepared to align your workflow with the tool’s happy path.

If you can’t find a tool that meets your requirements, write one.  I’ve done this many times over the years and so have thousands of our fellow developers.

At work, I spend 100% of my time on C# .NET application design, architecture, and coding. After work, it’s JavaScript and .NET.

I’ve found a sweet spot for my JavaScript development that I’ve written about in these two recent blog posts:

When writing JavaScript applications, I like that my tests run automatically any time I save a code or test file. Automatic is the operative word, not having to run an additional command for my tests to run saves time and effort.  The test results appear in a command line window.  Automatic test running enables simple red-green-refactor workflow written about by so many developers and unit test advocates.

Additionally, I’ve  grown fond of the BDD style assertions that the Chai library offers.

.NET Red-Green-Refactor Workflow

This section is about setting up a red-green-refactor code-time workflow. None of the below content applies to setting up a CI Server that performs continuous integration and testing services.

I’ve started work on my Ocean Framework that I originally published by in 2007. Back then I didn’t provide unit tests, a mistake I’m now correcting. I’ll write much more about Ocean and other WPF projects later in the year.

My workflow goal is:

  • Visual Studio automatically running the unit tests
  • BDD style assertions
  • Unit test framework that supports Xamarin, WPF, and C# libraries

I did my research and found that JetBrains Resharper Ultimate when combined with JetBrains dotCover provides .NET developers the capability to have a simple Continuous Testing workflow. Since I already have a JetBrains Ultimate license, this was an easy decision.  I also use JetBrains WebStorm and dotPeek products.

JetBrains Continuous Testing workflow enables developers to write code and unit tests, and when the files are saved automatically run the unit tests. Continuous Testing only runs tests that are impacted by a code or unit test change. When I have a project that has a thousand or two thousand unit tests, I’ll write a  blog post with the results of the time savings as well as the required system resources to support this feature.

Code coverage report is generated when tests are run and is viewed in the same tool window as the test results. The coverage report tool can also highlight your code, visually indicating the lines of code covered and not covered by the last unit test run. Nice feature when you’re driving for 100% coverage.

Continuous Testing has several options for triggering when tests are run.  I’m currently using the On ‘Save’ Build and Run Dirty Tests option as it meets my workflow requirements. Choose the option that best meets your workflow requirements.

continuoustesting

Continuous Testing allows developers to deselect assemblies or parts of assemblies not to run tests or coverage for, which is a fabulous feature for the red-green-refactor workflow as it cuts down the test run time significantly on large projects.

I should note, that Visual Studio has these same capabilities to run unit tests and provide code coverage report as well other excellent code analysis tools. You can quickly set up a shortcut key for running your tests on demand.  I could not figure out how to do this automatically. I did think about setting up a file watcher and then running the unit tests from the command line when a file is saved. Since JetBrains Continuous Testing does this for me, as well as only running the tests affected by files that are saved, I’ve selected this tool.

Choose the tools that meet your requirements and align with your workflow. If you like the Visual Studio tools, please use them.  No need to purchase tools if you don’t need them.

Tool Choices

I’ve chosen these libraries to round out my tooling selection. Use NuGet to install them the solution test assemblies.

Please do your research and select tools that meet your requirements and enable an effective code-time workflow.

Close

Reviewing daily workflow scenarios for efficiency and accuracy is an important task for developers and developer leads. Forming habits that make you efficient increases your value in the marketplace. Work smarter not harder.

Have a great day,

Just a grain of sand on the world’s beaches

 

Xamarin Dev Days Cranbury NJ

Infragistics is hosting Xamarin Dev Days on 19 Nov 2016 at our corporate office in Cranbury, NJ.

The very popular Xamarin Dev Days event sold out in one day, but there is a wait list and you can register here.

In addition to the standard curriculum, there will be an optional Bonus Content session given by Infragistics Engineers that wrote the Infragistics Xamarin Forms product.

Attend the fun day of learning with fellow developers and MVP’s at our excellent facility.

Have a great day,

Just a grain of sand on the world’s beaches

 

 

 

Open Source – cave lupum

Introduction

I’ve been actively working with open-source JavaScript packages for about 18 months. Developers that are very generous with their time have built tools and frameworks that have enriched the lives of developers all over the world. I too have contributed tools and believe in this beautiful Ecosystem.

A few months ago I started to look under the hood of my SPA and Nodejs applications and found code and practices that caught my attention. I found packages that other packages depended on, have very few lines of code. Packages with dependencies that are out of date or dependencies that had warnings such as, this package version is subject to a denial of service attack.

Upon further reflection, I got very concerned about the damage a bad person could inflict on trusting developers that download packages that have a dependency that has been replaced by evil code. My system and software that I write could be compromised. Now imagine ticking time bomb code replicated over Docker Containers and placed on servers. Damage could be immeasurable.

cave lupum – Beware the wolf disguised as a lamb.

Publicly articulating details of the many attack scenarios I’ve thought of would be irresponsible. Instead, it’s time to start the conversation around the problem that our international community is currently faced with and how we can protect our precious open-source.

Again, this blog post is about getting the conversation started.

Over the last few weeks, I’ve met with high profile MVP’s and a few corporate executives that share similar quality and security concerns that I’m sharing in this blog post.

For the purpose of this blog post, “packages” refers to open-source JavaScript packages that are added to Nodejs, or JavaScript web applications using a package manager.

I’ll have a section down below for compiled downloads such as NuGet, Visual Studio Gallery, and the Visual Studio Marketplace.

Proposal Goals

  • Not add any burdens to the open-source developer
  • Provide package consumers a measured level of confidence in the package and its dependencies
  • Raise the quality of packages by having them evaluated
  • Have repositories provide evaluation services and reporting for their packages

Proposal

Package evaluation is performed in the cloud.  An MVP friend also thought about a command line tool that could be used locally.

Package evaluation should be opt-in.  Allow developers wanting their packages evaluated to submit their package for evaluation. An opt-in approach would not add any burdens to developers not wanting to participate, while at the same time, driving up quality for the packages that are evaluated, giving those developers additional credibility for their efforts.

Consumers of packages could choose to use evaluated packages or continue to use non-evaluated packages at their own risk.

Evaluation and Download

Where packages are evaluated (centralized vs. non-centralized) is a topic that will generate much discussion and debate.

Where evaluated packages are downloaded from (centralized vs. non-centralized) is another topic that will generate much discussion and debate.

Evaluation Metrics

A standard set of metrics is applied to JavaScript packages, yielding a consistent evaluation report, enabling consumers to easily compare packages.

Below is a short “starter list” of metrics. Additional metrics should include the warnings such as those that npm emits when packages are installed.

Most evaluation metrics are yes or no.  Some are numeric; others are a simple list. When a package is evaluated, all of its dependencies are also evaluated. A package’s evaluation can only be as good as its weakest dependency.

  • Package signed
  • Included software license
  • Number of dependencies
  • Number of dependencies with less than ten lines of JavaScript
  • Package is out of date
  • Package has warnings
  • Have out of date dependencies
  • Has dependencies with warnings
  • Has unit tests
  • Has 100% unit test coverage
  • All tests pass
  • Makes network calls
  • Writes to file system
  • Threat assessment
  • Package capabilities (what API’s are being used)

NuGet, Visual Studio Gallery, Visual Studio Marketplace

NuGet, Visual Studio Gallery, and Visual Studio Marketplace serve compiled code which is evaluated differently than JavaScript. Microsoft will need to determine the best way to evaluate and report on these packages.

Funding

This proposal affects developers and infrastructures from all over the world.

As a software engineer, I know that while there will be challenges, the problems identified in this proposal are solvable.

Getting big corporations and government to proactively and cooperatively, take on and complete a task because it’s the right thing to do is a challenge that must be initiated.

Waiting until there is a problem and then trying to stem the tide and roll back the damage is a poor strategy.  Benjamin Franklin said, “an ounce of prevention is worth a pound of cure,” he is correct.

I honestly do not believe getting funding for a project of this scope will be any problem.

Next Steps

Big players need to meet and solve this problem.

Developers, start the conversation in your sphere of influence and contact big players and let them know your concerns.  Request that they take proactive action now.

Close

Have a great day.

Just a grain of sand on the worlds beaches.

 

XAML Designer Brush Editor Fixed

Introduction

Since the release of Visual Studio 2015 Update 3, the VS XAML Designer pop up brush editor quit working in the Properties window when properties were sorted by name, or when properties of type brush were not in the Brush category.  This issue affected both Visual Studio and Blend for Visual Studio 2015.

Fix

Microsoft posted the fix in this cumulative servicing update:

Microsoft Visual Studio 2015 Update 3 (KB3165756)  

https://msdn.microsoft.com/en-us/library/mt752379.aspx

I have installed the update and tested various controls and use cases and can confirm the fix corrected the problem.

Close

Have a great day.

Just a grain of sand on the worlds beaches.