Thursday, January 10, 2019

Better HTML5 Input Fields

HTML5 boldly came with the claim that it would offer more realistic input fields able to serve the needs of web applications. Apparently the HTML5 standards supports a long list of input types well beyond the historical short group of text, password, checkbox, radio, file, and button form input fields. The new list includes date/time specific input fields and types of input fields to accept ad hoc data such email addresses, URLs, phone numbers and plain numbers. The syntax of the INPUT element was extended to make up for new features. For example, the date input field now recognizes two extra attributes such as min and max to denote the earliest and latest dates that the control can accept.

It’s not gold all that shines though. Much of the work is left to browsers, and browsers, for a number of reasons, don’t typically hard-code much of the behavior that one might expect. In particular, no browser would check the validity of the input the user entered until the form is submitted. This means that users are apparently allowed to type any sort of characters in, say, a numeric input field just to find out that the input is invalid when they push the submit button. The same thing happens for phone numbers, websites, email addresses, dates and the like.

Finding a workaround is not a hard task, but it takes a bit of JavaScript code. Worse yet, it takes a bit of JavaScript code that must be written over and over again for every single use of any of the rich HTML5 input fields. This article intends to provide a jQuery-based JavaScript library—just a bunch of selectors actually—that when loaded into a layout page will extend a standard and more specific behavior to some HTML5 input fields. In particular, the library will automatically pre-process a number of HTML5 input fields adding to them the ability to react to invalid input on the blur event. The benefit for web developers is that you only need to reference the JavaScript library and that’s it—all will happen silently and effectively.

Although the library is provided as a jQuery extension, it wouldn’t take much to adapt jQuery selectors to plain DOM selectors and make it work even without jQuery.

Covered Use Cases

The HTML form input fields being modified in this article is described in the table below that lists the type of the input field and the implemented changes.

INPUT

DESCRIPTION

<input type=”email” />

Validate the email address as the user tabs out based on a fixed regular expression

<input type=”url” />

Validate the URL as the user tabs out based on a fixed regular expression

<input type=”tel” />

Validate the phone number based as the user tabs out based on user-defined regular expression

<input type=”number” />

Forces the user to only enter digits and automatically refuses any number outside the min/max range.

<input type=”password” />

Adds a button to toggle the type of the field between password and text allowing users to read the current password in clear.

<input type=”text” />

Honors the pattern attribute when the user tabs out of the field.

Let’s find out more and proceed case by case. Note that to exercise more control over validation phase of HTML5 forms, you might want to check out the spec of the validity browser API.

Validating Email Addresses

Certainty vanishes suddenly when it comes to validating emails. Every application, depending on the locales, may have different edge cases. HTML5 browsers do have a built-in engine to validate email addresses but, as mentioned, validation is only triggered upon form submission. If you want to have the email validated as soon as the user tabs out of the input field, then some ad hoc JavaScript is the only option left.

Here’s the skeleton of the JavaScript you want to have in place in all of your web pages with some HTML forms.

$("input[type=email]").on("blur",
    function () {
        var email = $(this).val();
        var re = / ... /;
        var success = re.test(email);
        if (success)
            $(this).removeClass("is-invalid");
        else
            $(this).addClass("is-invalid");
    });

A handler for the DOM blur event is set up for any INPUT element with the type attribute set to email. The jQuery-based body of the handler first grabs the current value of the input field and then checks it against a provided regular expression.

// YBQ FORMS
var success = re.test(email);

If the check is successful, then input field removes any is-invalid CSS class it may have. Otherwise, the input field just adds the is-invalid CSS class. Note that is-invalid is a Bootstrap 4 specific class aimed at rendering input fields with a red border to notify the invalid state. Needless to say, if you do not wish to use Bootstrap 4 to style your web page, then you’re welcome to apply any other CSS transformation to the DOM that reflects the invalid state of the element.

There’s a bit more you want to do, however, in the blur handler. First, you might want to deal with an empty or whitespace content. A blank field is valid or not? The idea here is to use the HTML5 required attribute to settle the question. If required is found, then the blank content should be parsed against the regular expression, otherwise, any further check is skipped and the content is validated.

$("input[type=email]").on("blur",
    function () {
        var email = $.trim($(this).val());
        var required = $(this).attr("required") != null;
        if (email.length === 0 && !required)
            return;

        // more code ...
});

Second, you can use the HTML5 pattern attribute to indicate a form-specific regular expression for the handler to process. If the attribute is not specified then the handler uses a built-in regular expression. Check out the source code for details.

$("input[type=email]").on("blur",
    function () {
        var email = $.trim($(this).val());
        var required = $(this).attr("required") != null;
        if (email.length === 0 && !required)
            return;
        var re = / ... /;
        var pattern = $(this).attr("pattern");
        if (pattern != null) {
            re = new RegExp($(this).attr("pattern"));
        }
        var success = re.test(email);
        
        // more code ...
});

The net effect is shown in the figure below. Note that most browsers also provide detailed error messages in the form of tooltips. Note also that the error message displayed through the tooltip is based on the browser’s internal email regular expression which might be different from the one hard-coded in the library or that you may have set through the pattern attribute. To turn off the tooltip, you just set the title attribute of the INPUT field to the empty string or anything else you like.

Validating URLs

Validating a URL input field poses exactly the same challenges as validating an email address as in the HTML5 spec. The type url supports the same attributes as the type email. Here’s then the code you need to have in place.

$("input[type=url]").on("blur",
    function () {
        var url = $.trim($(this).val());
        var required = $(this).attr("required") != null;
        if (url.length === 0 && !required)
            return;
        var re = / ... /;
        var pattern = $(this).attr("pattern");
        if (pattern != null) {
            re = new RegExp($(this).attr("pattern"));
        }

        var success = re.test(url);
        if (success)
            $(this).removeClass("is-invalid");
        else
            $(this).addClass("is-invalid");
});

For details about the default regular expression used to check the scheme of the URL refer to the source code.

Validating Phone Numbers

The code to extend input fields of type tel is slightly simpler and for a good reason: there’s nearly no chance that someone can come up with a sufficiently agreed, default regular expression for validating phone numbers. Because of this, the sample library doesn’t even attempt to support a default regular expression and just uses any expressions provided through the HTML5 pattern attribute. This makes the overall blur handler a bit shorter, as below.

$("input[type=tel]").on("blur",
    function () {
        var tel = $(this).val();
        var required = $(this).attr("required") != null;
        if (tel.length === 0 && !required)
            return;
 
        var re = new RegExp($(this).attr("pattern"));
        var success = re.test(tel);
        if (success)
            $(this).removeClass("is-invalid");
        else
            $(this).addClass("is-invalid");
    });

This said, what would be at least a good candidate to validate phone numbers? Here’s my shot at it:

<div class="form-group">
    <label for="phone">Phone</label>
    <input type="tel" class="form-control" 
           id="phone" name="phone" 
   pattern="[+][0-9]{1,3} [0-9]{3}[\s-][0-9]{4}[\s-][0-9]{3}"
           placeholder="+x xxx-xxxx-xxx">
    <div class="invalid-feedback">
        Phone number must be +x xxx-xxxx-xxx
    </div>
</div>

The phone number matched by the expression above is +X XXX-XXXX-XXX. To be precise, the dash (-) can also be replaced with a blank character. The international country code is up to three digits and number is grouped in three chunks of 3, 4, 3 digits respectively.

Accepting Numbers

Personally, I just hate to be able to type anything into a textbox only to receive a warning through a tooltip and an error message later. If the input field is declared to be of type number, then users should never be able to type in anything but digits. Here’s how to do it.

$("input[type=number]")
    .on("keypress",
        function (event) {
            if (event.charCode < 48 || event.charCode > 57) {
                event.preventDefault();
                return false;
            }
        })
    .on("keyup", function () {
        var buffer = $(this).val();
        var maxLength = parseInt($(this).attr("maxlength"));
        if (buffer.length > maxLength) {
            $(this).val("");
            return false;
        }
        var minVal = parseInt($(this).attr("min"));
        var maxVal = parseInt($(this).attr("max"));
        var number = parseInt(buffer);
        if (number < minVal || number > maxVal) {
            $(this).val("");
            return false;
        }
        return true;
    });

There are two handlers: one for keypress and one for keyup. The former refuses any keyboard button different from 0-9 digits. Admittedly, this implementation doesn’t support anything but positive integers. The keyup handler, instead, ensures that any number typed falls within the defined min/max range.

HTML5, in fact, allows you to set a min and a max attribute on numeric fields to delimit the range of feasible values. However, those boundaries are not checked until the form is submitted. With the keyup implementation, instead, the current value of the buffer is turned into an integer, checked against the min/max interval and emptied if it falls outside. In this way, the input field only returns integers (or blanks) in the given range.

In addition, the keyup handler also ensures that no more digits than maxlength are ever typed. The point is that, even though the range is, say, 1-20 and no value outside 1-20 will ever be allowed when tabbing out, then there’s no reason for the user to be able to type in more than 2 digits.

Extended Password Input Fields

The HTML5 spec adds a couple of features on password input fields that alone reduce the need for validating the password at least on the client. They are minlength and maxlength attributes, whose meaning is quite self-explanatory. In addition, HTML5 password input fields also support the pattern attribute which can be set to a JavaScript acceptable regular expression. In all these cases, though, remains the issue that any validation is performed when it might be annoying for users to note—upon form submission. Here’s how to add prompt notification of min/max length violation in the proposed password.

$("input[type=password]").on("blur",
    function() {
        var pswd = $.trim($(this).val());
        var minLength = parseInt($(this).attr("minlength"));
        var maxLength = parseInt($(this).attr("maxlength"));
        if (isNaN(minLength)) {
            minLength = 0;
        }
        if (isNaN(maxLength)) {
            maxLength = 100;
        }
        if (pswd.length < minLength || 
            pswd.length > maxLength)
            $(this).addClass("is-invalid");
        else
            $(this).removeClass("is-invalid");
    });

Quite simply, the blur handler captures the value of the minlength and maxlength attributes, turns them into numbers and compares with the actual length of the password buffer. Leading and trailing blanks are automatically removed. The password field also supports a pattern attribute for you to add some regular expressions to parse the proposed password. To add support for the pattern, just copy the same code seen above for email and URL fields.

One more thing you can do for password fields is adding—automatically—a button to switch between the password and text mode so that the password can be seen in clear.

The necessary code is shown below. You just add it to the input field reference side by side with the blur handler.

$("input[type=password]").each(function() {
    $(this)
        .add(
            "<span class='input-group-btn'>" +
            "<button type='button' class='btn btn-primary' 
             onclick='__togglePswdView(this)'>" +
            "<i class='fa fa-eye'></i></button></span>")
        .wrapAll("<div class='input-group' />");
}).on("blur", function() {
    // blur handler body
});

The code just uses the Bootstrap 4 markup for input button groups and attached some plain JavaScript code to toggle the value of the password’s type attribute.

function __togglePswdView(elem) {
    var pswd = $(elem).closest("div").find("input");
    var type = $(pswd).attr("type");
    if (type === "password")
        pswd.attr("type", "text");
    else
        pswd.attr("type", "password");
}

Controlling Input in Text Fields

Sometimes input fields are only allowed to take digits, letters and perhaps a few extra chars. You can use the pattern attribute set to a regular expression but if you do so you also need some of the aforementioned JavaScript to force the expression to be matched during the blur event.

$("input[type=text]").on("blur",
    function () {
        var text = $(this).val();
        var re = /(?:)/;
        var pattern = $(this).attr("pattern");
        if (pattern != null) {
            re = new RegExp($(this).attr("pattern"));
        }
        var success = re.test(text);
        if (success)
            $(this).removeClass("is-invalid");
        else
            $(this).addClass("is-invalid");
    });

In this way, to force an alphanumeric input, you only need the following regular expression.

<input type="text" class="form-control" 
       id="username" name="username"
       pattern="[a-zA-Z0-9]" />

Summary

HTML5 is now widely supported across modern browsers, but it pays for the goal of being a broad specification. As far as INPUT fields are concerned, there are plenty of options and a good enough range of attributes. The only problem is when those attributes are honored. Validation always takes place when the form is submitted, but this is not ideal for most scenarios when you want to give users immediate feedback about what they may have been doing wrong. In this case, JavaScript is necessary and the Ybq free library that comes with this article makes it trivially easy to trigger validation when and how you most need it. The source code is available here.

 

The post Better HTML5 Input Fields appeared first on Simple Talk.



from Simple Talk http://bit.ly/2VJ0Lzt
via

Wednesday, January 9, 2019

SQL naming conventions

SQL naming conventions for tables, and all the associated objects such as indexes, constraints, keys and triggers, are important for teamwork. Poorly-named tables and other objects make it difficult to maintain databases.

Table names must follow the rules for SQL Server identifiers, and be less than 128 characters. It is possible to force SQL Server to accept non-standard table names by surrounding them with square brackets but it is a very bad idea, because they have to be ‘quoted’ whenever they are used in scripts.

Temporary table names are slightly different in that they are prefixed with a single number sign (#) and are limited in length to 116 characters. After any prefix with a special meaning (‘@’ meaning a table variable, ‘#’ meaning a temporary table or ‘##’ meaning a global temporary table), the first letter must be a letter as defined by Unicode Standard 3.2. This means that it is either a Latin character from A through Z, upper or lower case, or else a letter character from other languages. Subsequent characters can legally be

  • Letters as defined in the Unicode Standard 3.2.,
  • Decimal numbers from either Basic Latin or other national scripts,
  • The ‘at sign’(@) , the ‘dollar sign’ ($), the ‘number’ or ‘hash sign’ (#)
  • The underscore, normally used to represent spaces such as Overdue_Account.

Never use spaces, embedded characters or reserved names, because they aren’t portable, require square brackets, and can confuse scripts and procedures.

We can test for compliance with SQL Server identifier spec very simply with the following SQL.

SELECT name FROM sys.objects 
   WHERE name LIKE '%[^_A-Z0-9@$#]%' COLLATE Latin1_General_CI_AI
 --contains illegal characters
   OR name NOT LIKE '[A-Z]%' COLLATE Latin1_General_CI_AI
 --doesn't start with a character

We can check for reserved words in objects in this slightly bulky but efficient code

SELECT name
  FROM sys.objects
    INNER JOIN
      (
      VALUES ('ADD'), ('EXTERNAL'), ('PROCEDURE'), ('ALL'), ('FETCH'),
        ('PUBLIC'), ('ALTER'), ('FILE'), ('RAISERROR'), ('AND'),
        ('FILLFACTOR'), ('READ'), ('ANY'), ('FOR'), ('READTEXT'), ('AS'),
        ('FOREIGN'), ('RECONFIGURE'), ('ASC'), ('FREETEXT'), ('REFERENCES'),
        ('AUTHORIZATION'), ('FREETEXTTABLE'), ('REPLICATION'), ('BACKUP'),
        ('FROM'), ('RESTORE'), ('BEGIN'), ('FULL'), ('RESTRICT'), ('BETWEEN'),
        ('FUNCTION'), ('RETURN'), ('BREAK'), ('GOTO'), ('REVERT'), ('BROWSE'),
        ('GRANT'), ('REVOKE'), ('BULK'), ('GROUP'), ('RIGHT'), ('BY'),
        ('HAVING'), ('ROLLBACK'), ('CASCADE'), ('HOLDLOCK'), ('ROWCOUNT'),
        ('CASE'), ('IDENTITY'), ('ROWGUIDCOL'), ('CHECK'), ('IDENTITY_INSERT'),
        ('RULE'), ('CHECKPOINT'), ('IDENTITYCOL'), ('SAVE'), ('CLOSE'), ('IF'),
        ('SCHEMA'), ('CLUSTERED'), ('IN'), ('SECURITYAUDIT'), ('COALESCE'),
        ('INDEX'), ('SELECT'), ('COLLATE'), ('INNER'),
        ('SEMANTICKEYPHRASETABLE'), ('COLUMN'), ('INSERT'),
        ('SEMANTICSIMILARITYDETAILSTABLE'), ('COMMIT'), ('INTERSECT'),
        ('SEMANTICSIMILARITYTABLE'), ('COMPUTE'), ('INTO'), ('SESSION_USER'),
        ('CONSTRAINT'), ('IS'), ('SET'), ('CONTAINS'), ('JOIN'), ('SETUSER'),
        ('CONTAINSTABLE'), ('KEY'), ('SHUTDOWN'), ('CONTINUE'), ('KILL'),
        ('SOME'), ('CONVERT'), ('LEFT'), ('STATISTICS'), ('CREATE'), ('LIKE'),
        ('SYSTEM_USER'), ('CROSS'), ('LINENO'), ('TABLE'), ('CURRENT'),
        ('LOAD'), ('TABLESAMPLE'), ('CURRENT_DATE'), ('MERGE'), ('TEXTSIZE'),
        ('CURRENT_TIME'), ('NATIONAL'), ('THEN'), ('CURRENT_TIMESTAMP'),
        ('NOCHECK'), ('TO'), ('CURRENT_USER'), ('NONCLUSTERED'), ('TOP'),
        ('CURSOR'), ('NOT'), ('TRAN'), ('DATABASE'), ('NULL'), ('TRANSACTION'),
        ('DBCC'), ('NULLIF'), ('TRIGGER'), ('DEALLOCATE'), ('OF'),
        ('TRUNCATE'), ('DECLARE'), ('OFF'), ('TRY_CONVERT'), ('DEFAULT'),
        ('OFFSETS'), ('TSEQUAL'), ('DELETE'), ('ON'), ('UNION'), ('DENY'),
        ('OPEN'), ('UNIQUE'), ('DESC'), ('OPENDATASOURCE'), ('UNPIVOT'),
        ('DISK'), ('OPENQUERY'), ('UPDATE'), ('DISTINCT'), ('OPENROWSET'),
        ('UPDATETEXT'), ('DISTRIBUTED'), ('OPENXML'), ('USE'), ('DOUBLE'),
        ('OPTION'), ('USER'), ('DROP'), ('OR'), ('VALUES'), ('DUMP'),
        ('ORDER'), ('VARYING'), ('ELSE'), ('OUTER'), ('VIEW'), ('END'),
        ('OVER'), ('WAITFOR'), ('ERRLVL'), ('PERCENT'), ('WHEN'), ('ESCAPE'),
        ('PIVOT'), ('WHERE'), ('EXCEPT'), ('PLAN'), ('WHILE'), ('EXEC'),
        ('PRECISION'), ('WITH'), ('EXECUTE'), ('PRIMARY'), ('WITHIN GROUP'),
        ('EXISTS'), ('PRINT'), ('WRITETEXT'), ('EXIT'), ('PROC')
      ) AS reserved (word)
      ON reserved.word = sys.objects.name;

 

Beware of numbers in any object names, especially table names. It normally flags up clumsy denormalization where data is embedded in the name, as in ‘Year2017’, ‘Year2018’ etc. Usually the significance of the numbers is obvious to the perpetrator, but not to the maintainers of the system.

SELECT name FROM sys.tables
   WHERE name LIKE '%[0-9]%' COLLATE Latin1_General_CI_AI --contains numbers

If you are more relaxed about this and will tolerate single numbers but no more, then tyy this

SELECT name FROM sys.tables
   WHERE name LIKE '%[0-9][0-9]%' COLLATE Latin1_General_CI_AI 
–contains more than one adjacent number

There are no generally accepted standards for naming SQL objects. Although ISO/IEC 11179 has been referred to as a standard for naming, it actually only sets a standard for defining naming conventions. There is a sample standard in the ‘Naming principles’ document (ISO/IEC 11179-5), but this is merely an example of how a standard should be defined. However, it is quite close to a general good-practice in programming.

When naming a table, it is a good idea to use a collective name or ‘object class term’ for the entity if one exists ( such as Employee, Cost, Tree, component, member, audience, staff or faculty) but use the singular rather than the plural form where possible. For the sake of maintenance, use a consistent naming convention that is informative but brief. It helps greatly to start with a dictionary of the correct nouns and verbs associated with the application domain and use that. If it proves inadequate, then the team can build on it. If a data model has been created as part of the design phase, this dictionary should be an end-product of this work.

Never use a descriptive prefix such as tbl_. This ‘reverse-Hungarian’ notation has never been a standard for SQL and clashes with SQL Server’s naming conventions. Some system procedures and functions were given prefixes “sp_”, “xp_” or “dt_” to signify that they were ‘special’ and should be searched for in the master database first. The use of the tbl_prefix for a table, often called ‘tibbling’, came from databases imported from Access when SQL Server was first introduced. Unfortunately, this was an access convention inherited from Visual Basic, a loosely typed language. Even if prefixes were a good thing, one wouldn’t use “Tbl_” for a table. There are established codes for SQL Server and the code for a table is U (short for ‘User Table’ evidently). There are still many DBAs that long to ‘tibble’, but there is never a doubt what type of object something is in SQL Server if you know its name, schema and database, because its type is there in sys.objects: Also it is obvious from the usage. SQL Server is a strongly-typed language.

SELECT name FROM sys.objects 
  WHERE Left(name,3) IN ('tbl','sp_','xp_','dt_')  --tibbling!

Do not give a table the same name as one of its columns.

SELECT Thetable.Name FROM sys.columns cols
INNER JOIN sys.tables Thetable 
  ON Thetable.object_id = cols.object_id
  WHERE cols.NAME=Thetable.name

Avoid, where possible, concatenating two table names together to create the name of a relationship table when there is already a word in the language to describe the relationship. e.g. use Client rather than EmployeeCustomer

This code will find these tables. Don’t try it on a huge database!

SELECT name
  FROM sys.tables AS TheTable
    INNER JOIN
      (
      SELECT first.name + second.name
        FROM sys.tables AS first
          CROSS JOIN
            (SELECT name FROM sys.tables) AS second
      ) AS combined(doubleName)
      ON combined.doubleName = TheTable.name;

On AdventureWorks2016, you will get a few tables that could be better-named

Keep table names short, because many naming conventions require that triggers, constraints and indexes include the name of the table or tables involved. A foreign key constraint can get cumbersome

Be consistent in the casing of tables and the use of underscore for delimiting words.

A table column should be a ‘quality common to all members of an object class’ and should have a name that corresponds to the way that plain language refers to the property such as First_Name, Amount, Measure, Number, Quantity or Text. Never apply the collective name to the property, such as having an ‘Employee_name’ property in an Employee table. This would provide redundancy when the qualified column was listed in a query – Employee.Employee_name.

You can quickly find all the columns with redundancy in their names if they are expressed with the dotted notation.

SELECT TheTable.name AS TableName, TheColumn.name AS ColumnName
  FROM sys.tables AS TheTable
    INNER JOIN sys.columns AS TheColumn
      ON TheColumn.object_id = TheTable.object_id
  WHERE TheColumn.name LIKE '%' + TheTable.name + '%';

AdventureWorks is full of this sort of problem.

Whoever thought up the name Person.Person.personType was short on vocabulary. It might be an idea to detect for the even more heinous crime of naming a table the same as a schema!

SELECT name FROM sys.objects WHERE Object_Schema_Name(object_id) = name;

A simple guide to naming is to respect the idea of SQL being an intelligible language based on written language. This would suggest that function names should fit into the semantics of the SELECT sentence, if we have a function that capitalises a sentence, makes the first character of each word longer than three characters a capital letter (MLA), then you’d call it ‘capitalized()’. Procedures would be verb-noun names of tasks, since they are executed.

Procedures should follow the Verb-noun convention popularised by PowerShell. Obviously, the standard verbs and nouns will come from the database design process and the data model of the organisation or the application domain.

Summary

There are certain style rules in SQL Server, but not that many. It is more important to be consistent and, where possible, write in a way that is closest to standard SQL. SQL Server gives you quite a bit of latitude in your style, but because you can do such things as putting numbers, whitespace and control characters into names doesn’t mean that you should. You can write in eccentric archaic dialects of SQL, but you are still being eccentric. In teamwork, it is best to adopt the defined standard that is in place, however absurd it may be, and work away at convincing the rest of the team to change.

SQL is unlike any other computer language in that it was designed to be as close to human language as possible, so it could be used by lay people to do business analysis. I believe that naming conventions should fit in with this basic idea so that database code reads clearly with just the minimum of documentation to assist in understanding.

See SQL Code Smells for more SQL Smells. See SQL Server Table Smells for SQL Code that flushes out more general problems with tables

The post SQL naming conventions appeared first on Simple Talk.



from Simple Talk http://bit.ly/2QxxNPu
via

The Case for Value-Based Delivery

In the past, I was very proud that I’d meticulously defended my projects against scope creep, but I was missing the point. The real reason organizations should undertake projects is to achieve value.

What should be the priority, then, defending against scope creep or value-based delivery? The agile movement fundamentally understands this. Its core principles acknowledge that requirements will change as understanding grows. However, if you look at traditional agile tools and concepts—like the burn up (or burn down) chart and the cone of uncertainty— you’ll see they are often scope-oriented.

The most important question project managers should ask themselves about any project is not “What?” but “Why?” The business case for project execution could be reducing OPEX costs or meeting compliance goals, for example. When you understand the outcome your organization or client is seeking, you will know where to direct your team and efforts.

We recently worked on a project to develop a system for a legacy customer. They did not have a system for efficiently managing interactions with the international healthcare community (healthcare professionals, patient organizations, etc.). Considering the scope of the project, it was easy to plan and deliver, but we later realized that the project had gone over budget and was extended by a couple of months. This was because of continuous growth in the project’s scope.                         

Was this a failure? I could have defended all scope changes. After the delay and going over budget, we delivered the project. The new system drove the customer’s commercial business as well as contributing to the discovery and progress of Research and Development. The customer is highly regulated and at high risk in life sciences. We were able to deliver standardized processes across international customers, provided transparency of professional’s use, and enabled compliance monitoring for risk mitigation.

Defining and reporting against these additional requirements was far more challenging than simply relying on scope, time and cost but gave us much more confidence that we were delivering business value. This approach requires very rigorous thinking and a real understanding of what it takes to deliver success. In my experience, the ability to help define the drivers of success is one of the skills that makes a project manager a great business partner.

As another example, the Sydney Opera House could probably be seen as one of the most disastrous construction projects in history. The project was originally scheduled for four years, with a budget of AUS $7 million. It ended up taking 14 years to be completed at a cost of AUS $102 million. Do you see this as a failure?

Below are the project statistics which are available in public forums:

https://media.licdn.com/dms/image/C5612AQEigcxuwmO1aw/article-inline_image-shrink_1000_1488/0?e=1551312000&v=beta&t=sh7aCeX0KJU5dZlEbIxQ_37-jpF5V-bzU6AS5w15R6k

As a project, it was a failure, but as an idea, it was a huge success. It’s one of the 20th century’s most magnificent buildings and one of the 21st century’s busiest performing arts centers.

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post The Case for Value-Based Delivery appeared first on Simple Talk.



from Simple Talk http://bit.ly/2TAl1kX
via

Tuesday, January 8, 2019

Policy-based Authorization in ASP.NET Core – A Deep Dive

Take advantage of Policy-based authorization, a simple, rich, expressive and reusable authorization model, to secure your applications written in ASP.NET Core

Authentication and Authorization are two terms you would often come across when reading about the security of web applications. While the former is used to validate a user’s credentials, the latter is used to grant access to one or more resources of the application to a user. There are two ways in which you can implement authorization in ASP.NET Core. These include role-based authorization and policy-based authorization. Role-based authorization has been in use from the previous versions of ASP.NET. Policy-based authorization has been newly introduced in ASP.NET Core and provides a rich, expressive and reusable authorization model to secure applications developed in ASP.NET Core. This article presents a discussion on how you can work with policy-based authorization in ASP.NET Core.

Prerequisites

To work with the code examples provided in this article, you should have Visual Studio 2017 and NET. Core installed in your system. If you don’t have .NET Core installed in your system, you can download a copy from here. You can download Visual Studio 2017 from this link.

Before the deep dive into how the policy-based authorization model works, here’s a quick tour of the role-based security model to understand the constraints of the role-based security model and then learn why the policy-based authorization model should be used.

Role-based Authorization in ASP.NET Core

A role is a string value that is mapped to a set of permissions for an authenticated user. The role-based security model has been in use from the days of ASP.NET. Role-based authorization is a declarative way to restrict access to resources. You can specify the roles that the current user must be a member of to access a specified resource. The Authorize attribute enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method. If you specify this attribute without any arguments, it only checks if the user is authenticated. Here’s an example that illustrates how this attribute can be applied to a controller.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
public class UserController : Controller
{
  //Action methods
}

The following code snippet can be used to limit access to the SecurityController to only those users who are administrators, i.e., those users who are a member of the Administrator role.

[Authorize(Roles = "Administrator")]
public class SecurityController : Controller
{
  //Usual code
}

Multiple Roles

You can also specify multiple roles, separated by a comma. Here’s an example that illustrates this.

[Authorize(Roles = "Manager,Administrator")]
public class DocumentsController : Controller
{
   //Action methods
}

In this example, only those users who pertain to the Manager or Administrator role can have access to the DocumentsController and all its methods.

Note that you can apply roles both at the controller and the action levels. As an example, even if users having either Manager or Administrator roles can access the DocumentsController and its methods, you may want a method of this controller class to be accessed only by users who belong to the Administrator role. The following code snippet shows how this can be achieved.

[Authorize(Roles = "Manager, Administrator")]
public class DocumentsController : Controller
{
    public ActionResult ViewDocument()
    {
        //Your code here
    }
    [Authorize(Roles = "Administrator")]
    public ActionResult DeleteAllDocuments()
    {
        //Your code here
    }
}

Now, suppose you would want users who belong to both Manager and Administrator roles should only have access to the DocumentsController and its methods. The following code snippet shows how you can define roles in such a way that the users who access the DocumentsController and its methods must be a member of both Manager and Administrator roles.

[Authorize(Roles = "Manager")]
[Authorize(Roles = "Administrator")]
public class DocumentsController  : Controller
{
}

Albeit its ease of use, role-based authorization has its limitations. This is exactly why policy-based authorization is used. In the sections that follow you will examine how you can work with policy-based authorization in ASP.NET Core.

The Need for Policy-based Authorization

Authorization and access control using roles for protecting resources from unauthorized access have been in use for quite some time. However, they aren’t very expressive, and you may run into problems when the number of roles that are needed is significantly high.

Here’s a scenario with an example to explain. Suppose you are tasked with designing a security framework for an application. Initially, there are three roles in an application, i.e., User, Admin, and Manager. Now if you have multiple variations of the Admin role, like, CustomerAdmin, ReportsAdmin, and SuperAdmin, you would have to consider each of these when you are designing the security framework. You can also have multiple variations of the Manager role – your framework will have to consider these as well. As the number of these roles increases significantly, it becomes extremely difficult to effectively handle the roles. Here’s exactly where a policy-based authorization model comes in.

Working with Policy-based Authorization in ASP.NET Core

A policy-based security model decouples authorization and application logic and provides a flexible, reusable and extensible security model in ASP.NET Core. The policy-based security model is centered on three main concepts. These include policies, requirements, and handlers. A policy is comprised of several requirements. A requirement, in turn, contains data parameters to validate the user’s identity. Lastly, a handler is used to determine if a user has access to a specific resource. We’ll discuss each of these in more detail in this section – we’ll start with a policy.

Essentially, a policy is comprised of one or more requirements and is usually registered at application startup in the ConfigureServices() method of the Startup.cs file. To apply the policies in your controllers or action methods, you can take advantage of the AuthorizeAttribute attribute or the AuthorizeFilter filter.

You can create a policy instance using the AuthorizationPolicyBuilder class as shown in the code snippet given below. You can specify the role names using the RequireRole method.

var policy = new AuthorizationPolicyBuilder()
  .RequireAuthenticatedUser()
  .RequireRole("Admin")
  .Build();

Alternatively, you can create the policy instance in the ConfigureServices method as shown in the code snippet given below.

services.AddMvc(obj =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                obj.Filters.Add(new AuthorizeFilter(policy));
            });

You’ll see more on this in the sections that follow.

Registering a Policy

Merely defining the policies isn’t enough – you should also register the policies you’ve defined with the authorization middleware. To register a policy, you should specify a name – this name would be used to reference the policy in the controller or the action methods.

The following code snippet illustrates how a policy can be registered at application startup in ASP.NET Core.

using Microsoft.Extensions.DependencyInjection;
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireManagerOnly", policy => 
               policy.RequireRole("Manager"));
    });
}

You can also specify multiple allowed roles when registering the policy as shown in the code snippet below.

services.AddAuthorization(options =>
    {
        options.AddPolicy("RequireManagerOnly", policy => 
              policy.RequireRole("Manager","Administrator"));
    });

Applying the Policy

Once the policy has been registered, you can apply the policy in your controller or the controller’s action methods. If you were to apply the policy at the controller level, here’s how you would need to specify the policy.

[Authorize(Policy = "RequireAdminOnly")]
public class SecurityController: Controller
{
    //Action methods
}

As you can see, instead of specifying roles in the [Authorize] attribute, you can specify the policy that you would like to apply. To apply a policy to an action method, you can take advantage of the Policy property of the Authorize attribute as shown in the code snippet below.

[Authorize(Policy = "RequireAdminOnly")]
public IActionResult DeleteAllSecureDocuments()
{
    //Some code
}

You can also apply multiple policies to a controller or an action method. The following code snippet illustrates how this can be achieved.

[Authorize(Policy = "ShouldBeEmployeeOnly")]
public class SecurityController : Controller
{
    [Authorize(Policy = "RequireAdminOnly")]
    public ActionResult DeleteUser()
    {
        //Your code here
    }
}

In the above code example, you can see two policies applied – one at the controller level and the other at the action level. Refer to the DeleteUser action method in the code example above. This action method can be executed only by users who satisfy both the policies, namely ShouldBeEmployeeOnly and Administrator. In other words, to call the DeleteUser method, the identity must fulfill the two policies ShouldBeEmployeeOnly and Administrator.

Although role-based authorization is easy to implement in ASP.NET Core, it has limited scope. As an example, imagine that you need to validate a user based on the Joining date or Department Id. You cannot have roles for each of such variations – that’s not a good solution at all. Here’s where you can take advantage of claims-based authorization – you can validate the identity of a user based on the claims. The section that follows examines how you can work with claims-based authorization via policies.

Using Claims Based Authorization via Policies

Claims based authorization provides a declarative way of checking access to resources. In this type of authorization, you would typically check the value of a claim and then grant access to a resource based on the value contained in the claim. First off, understand what a claim is. A claim is a key-value pair that represents a subject, i.e., name, age, passportnumber, drivinglicense, passport, nationality, dateofbirth, etc. So, if dateofbirth is the claim name, the claim value would be the date of birth, i.e., 1st January 1970.

It should be noted that a claim is given to a trusted party only. As mentioned above, a claim represents the subject – tells you who the subject is. However, a claim has nothing to do with what the subject can do – it never tells you that.

Claims based authorization can be implemented using policies. In this section, you will explore how you can work with policy-based claims. The code snippet given below shows how a simple claim policy is registered. The ShouldBeOnlyEmployee policy looks for the presence of the EmployeeId claim. The policy is added to the services collection using the AddPolicy method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddAuthorization(options =>
    {
        options.AddPolicy("ShouldBeOnlyEmployee", policy => 
              policy.RequireClaim("EmployeeId"));
    });
}

You can then apply this policy at the controller level on the AuthorizeAttribute attribute as shown below.

[Authorize(Policy = "ShouldBeOnlyEmployee")]
public IActionResult SomeMethod()
{
    //Write your code here
}

You can have policies with multiple claims as well. You should register them appropriately in the ConfigureServices method of the Startup class as shown in the code snippet given below.

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddMvc().SetCompatibilityVersion(
          CompatibilityVersion.Version_2_1);  
    services.AddAuthorization(options =>  
    {  
        options.AddPolicy("CustomSecurityPolicy", policy => 
             policy.RequireClaim("ShouldBeOnlyEmployee"));  
        options.AddPolicy("CustomSecurityPolicy", policy => 
             policy.RequireClaim("IsAdmin", "true"));  
    });  
}

Requirements

Beneath the covers, both role-based and claims-based authorization techniques take advantage of a requirement, a handler, and a policy. In this and the subsequent sections each of these will be explored.

A requirement comprises a collection of data parameters. These data parameters are used by a policy to evaluate the user identity. To create a requirement, you need to create a class that implements the IAuthorizationRequirement interface. The following code snippet illustrates a requirement for the MinimumExp policy – you will register this policy in a while.

public class MinimumExpRequirement : IAuthorizationRequirement
{
    public int MinimumExp { get; set; }
    public MinimumExpRequirement(int experience)
    {
        MinimumExp = experience;
    }    
}

Authorization Handlers

A requirement can have one or more handlers. An authorization handler is used to evaluate the properties of a requirement. To create an authorization handler, you should create a class that extends AuthorizationHandler<T> and implements the HandleRequirementAsync() method. The following code snippet shows how a typical authorization handler looks.

public class MinimumExpHandler : 
     AuthorizationHandler<MinimumExpRequirement>
    {
        protected override Task HandleRequirementAsync(
               AuthorizationHandlerContext context, 
               MinimumExpRequirement requirement)
        {
            throw new NotImplementedException();
        }
    }

The following code snippet shows how you can write the necessary authorization logic in the HandleRequirementsAsync method to find a claim and evaluate the requirement.

public class MinimumExpHandler : 
          AuthorizationHandler<MinimumExpRequirement>
    {
        protected override Task HandleRequirementAsync(
               AuthorizationHandlerContext context, 
               MinimumExpRequirement requirement)
        {
            var user = context.User;
            var claim = context.User.FindFirst("MinExperience");
            if(claim != null)
            {
                var expInYears = int.Parse(claim?.Value);
                if (expInYears >= requirement.MinimumExp)
                    context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }

Now, how do I know whether a handler executed successfully, i.e., what should a handler return? Well, if a requirement has been successfully evaluated, you may want to call the Succeed method on the AuthorizationHandlerContext instance and pass the requirement instance as a parameter to the method. In the code snippet given above, note how the Succeed method has been called.

Multiple Handlers for a Single Requirement

As I said earlier, a requirement can also have multiple handlers. You might want to use multiple handlers for a requirement when you need to evaluate the requirement based on multiple conditions. As an example, you might want to check if the user is an employee and if the age of the employee is more than 50 years. So, for each of these conditions, you need to have a separate handler.

public class EmployeeRequirement : IAuthorizationRequirement
{
   //Write your code here
}
public class EmployeeRoleHandler : 
         AuthorizationHandler<EmployeeRequirement>
{
    //Write your code here to check if the user is an employee
}
public class MinimumAgeHandler : 
         AuthorizationHandler<EmployeeRequirement>
{
    //Write your code here to validate min age
}

Registering the handler

You should register handlers in the services collection. To register the handler created earlier in this article, you should write the following code in the ConfigureServices method of the Startup class as shown in the code snippet below.

public void ConfigureServices(IServiceCollection services)
        {
            //Other code
            services.AddSingleton<IAuthorizationHandler, 
            MinimumExpHandler>();
        }

Note the usage of the AddSingleton method in the ConfigureServices method given above. When working with dependency injection in ASP.NET Core, you can specify the service lifetimes using AddTransient, AddScoped, or AddSingleton methods. This example uses the singleton lifetime. When using this type of service lifetime, the service instance will be created the first time it is requested. Subsequent requests to the service will reuse the same instance. To know more on service lifetimes in ASP.NET Core, you can take a look at this article.

Here’s the complete code listing of the ConfigureServices method – both the policy and the handler is registered with the pipeline.

public void ConfigureServices(IServiceCollection services)
        {      services.AddMvc().SetCompatibilityVersion(
               CompatibilityVersion.Version_2_1);
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    "MinExperience", policy =>
                    policy.Requirements.Add(
                          new MinimumExpRequirement(5)));
            });
            services.AddSingleton<IAuthorizationHandler, 
                   MinimumExpHandler>();
        }

Summary

The authorization model in ASP.NET Core has had a major upgrade with the introduction of a simple, declarative, policy-based authorization model. Policy-based authorization is flexible and helps you to build a loosely coupled security model by decoupling the authorization and application logic. Incidentally, ASP.NET Core supports both role-based and policy-based authorization. This article examined the policy-based authorization model, its benefits, and how to work with it in ASP.NET Core.

 

The post Policy-based Authorization in ASP.NET Core – A Deep Dive appeared first on Simple Talk.



from Simple Talk http://bit.ly/2VCsfH9
via

Getting Started with GraphQL in ASP.NET

GraphQL has been around for a while and is proving its value. It is not, unlike what’s been spread about, a framework or just a ready-tool for dealing with HTTP-based searches. Just like REST is a specification to access resources that partially expose the business models in client-server applications, GraphQL is a cleaner, more flexible way to execute and fetch specific data from the server.

In other words: ask for hat you need, get exactly that. That’s the anthem of GraphQL. Instead of having tons of different REST endpoints to provide access to every resource via a different HTTP request, you can do the same thing with only a single request, along with a smarter (smaller – just what you need) response body, getting summarized data from different resources.

It also comes with a strong type system, encapsulated in a syntax that resembles JSON. Also, you don’t need to worry about versioning the endpoints since you can deprecate your fields once they become old. And it is available for all the major languages for both client and server sides. Because of its committed community, you can find many different open source clients and projects being broadly supported around the world.

General Architecture

Think about graphs. In theory, they are used to mathematically model the relations two objects have in common. In GraphQL, you start to join this concept with a query language in order to fetch/send all the data you need with no more endpoints.

In a common REST API, developers grab information from endpoints that represent a single and understandable source of information, a resource. Usually, they return a lot of data, most of this not necessary for the current operation, making the whole conversation too verbose. Plus, since each resource hosts different data, you’d need to go through many of them to catch everything turning the calling to the server too chatty:

GraphQL, on the other hand, summarizes everything the client needs at once, by allowing you to specify all the data in a query fully supported by the back-end. One single HTTP request, all the data you need in hands:

This way, GraphQL minimizes a lot of the over and under fetching issues that most modern applications deal with in addition to letting the front-end be freer to mount the request chaining the way they see it’s best.

Because of its HTTP-based nature, GraphQL also benefits from all the out-of-the-box features that REST did, including the stateless state, patterns, free from tech stack and heavily embraced by the community. Also, you can create your APIs within any supported language, just the same way you would with the clients. Most of the big platforms already support it.

Another important feature that comes with GraphQL are the resolvers. They basically allow the extraction of data from different sources and integrate the data into the same response. It is useful when you want to connect data that relates to the query objects are being fetched now, while accessing resources sometimes even via remote calls to other services. This architectural design, of course, can lead to slowness depending on the way you make each call. Remember, even though it’s a great feature to use, each integration you have in a single query can lead to more and more delay to the user’s response, so be careful just the same way you should be when designing REST web services. Finally, you also have to remember that a query still has to fetch relatable data, which means that a query that searches for a user data has nothing to do with your stockroom’s system data. So, keep anchored to your original design and make data design meaningful.

Demo Project

You have an idea about GraphQL basics, and now it’s time to practice with a relatable example. For this, you will go through an example that explores a comparison between an old fashion approach (REST) vs. the same thing with GraphQL. The Simple Talk author’s page will be the front-end client of a web service that returns the data necessary to build it.

In a common REST application, you’d have the following endpoints to retrieve the JSON/XML/etc. data:

  • /authors/{id} – the core information related to user of id referenced at {id} path param;
  • /authors/{id}/posts – the posts data related to user of id referenced at {id} path param;
  • /authors/{id}/socials – the social networks related to user of id referenced at {id} path param.

Therefore, REST is so chatty. For every new compositional data, that is related to a specific user, a new endpoint that identifies it is born, meaning that a new request must happen.

Instead, using GraphQL, you’d need a query like this one:

query GetBlogData($id: Int!) {
  author(id: $id) {
    // author core data
  }
  posts(id: $id) {
    // posts list
  }
  socials(id: $id) {
    // social networks list
  }
}

Inside of each query member, you can fetch just the exact information you want. It is contrary to REST, where each endpoint would return all the information related to a post or a social network, making the whole response heavier than what you need.

Environment and Setup

To get started, create a new ASP.NET Core Web Application called GraphQL-SimpleTalk using the New Project wizard in VS. You can use the Visual Studio Community Edition. For this, you must have the latest version of .NET Core SDK installed in your environment.

In the next screen, select the project template API.

Once with the project created, add the NuGet dependencies for GraphQL. Right-click the solution and go to NuGet manager. There, search for two dependencies:

  • GraphQL: the core, parsers, Linq adapters, etc.
  • GraphiQL: the UI necessary to perform the tests

That’s all. To simplify this article, you’ll create a service layer and manage objects in lists in memory. This way, you don’t have to worry about further integrations and details that don’t relate to the article purposes.

The Project Implementation

The first part of the project to create are the models. They’ll drive the rest of the implementation, and they are called entities (supposedly the ones that would attach to a database context). Take a look at the following diagram:

Idealistically, there would be more fields and relations happening here. However, this model keeps as close as possible to what is the ST’s authors page. Plus, the socials and posts models are separate from the author itself, since you’ll search them through the in-memory lists to return in separate service methods.

Continuing, inside the project, create a new folder Entities and create several classes.

The Author class:

namespace GraphQL_SimpleTalk.Entities
{
    public class Author
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Bio { get; set; }
        public string ImgUrl { get; set; }
        public string ProfileUrl { get; set; }
    }
}

The Comment class:

namespace GraphQL_SimpleTalk.Entities
{
    public class Comment
    {
        public string Url { get; set; }
        public string Description { get; set; }
        public int Count { get; set; }
    }
}

The Rating class:

namespace GraphQL_SimpleTalk.Entities
{
    public class Rating
    {
        public int Percent { get; set; }
        public int Count { get; set; }
    }
}

The Post class:

using System;
using System.Collections.Generic;
namespace GraphQL_SimpleTalk.Entities
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }
        public string Url { get; set; }
        public Author Author { get; set; }
        public string[] Categories { get; set; }
        public Rating Rating { get; set; }
        public List<Comment> Comments { get; set; }
    }
}

The SocialNetwork class:

namespace GraphQL_SimpleTalk.Entities
{
    public class SocialNetwork
    {
        public SNType Type { get; set; }
        public string NickName { get; set; }
        public string Url { get; set; }
        public Author Author { get; set; }
    }
    public enum SNType
    {
        INSTAGRAM, TWITTER
    }
}

Make sure to create each one of them in a separate class file. Here, you also had to change the namespace from GraphQL-SimpleTalk to GraphQL_SimpleTalk, because .NET doesn’t accept hyphens for names.

They’re just simple POJO (plain old Java objects) structural objects to simulate what you’d have in a real database-based API application. You can also turn them into DDD (Domain Driven Design) objects to host business logic or important operations for your API.

The SocialNetwork has an enum (SNType) to host the types of social media the author could possibly have. It will be interesting to demonstrate how to deal with enums in GraphQL as well.

Now, move to the service layer. You’re going to create a single service class that will provide access to the main data related to the blog. Since it’s not the focus of the project, not much time will be spent on it. Again, create a new folder Services and add the following class inside:

using GraphQL_SimpleTalk.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GraphQL_SimpleTalk.Services
{
    public class BlogService
    {
        private readonly List<Author> authors = new List<Author>();
        private readonly List<Post> posts = new List<Post>();
        private readonly List<SocialNetwork> sns = new List<SocialNetwork>();
        
        public BlogService()
        {
            Author DinoEsposito = new Author
            {
                Id = 1,
                Name = "Dino Esposito",
                Bio = "Dino Esposito has authored more than 20 books and 1,000 articles in ...",
                ImgUrl = "https://secure.gravatar.com/avatar/ace158af8dfab0e682dcc70d965514e5?s=80&d=mm&r=g",
                ProfileUrl = "https://www.red-gate.com/simple-talk/author/dino-esposito/"
            };
            Author LanceTalbert = new Author
            {
                Id = 2,
                Name = "Lance Talbert",
                Bio = "Lance Talbert is a budding game developer that has been learning to program since ...",
                ImgUrl = "https://www.red-gate.com/simple-talk/wp-content/uploads/2018/01/red-gate-bio-pic.jpg",
                ProfileUrl = "https://www.red-gate.com/simple-talk/author/lancetalbert/"
            };
            authors.Add(DinoEsposito);
            authors.Add(LanceTalbert);
            Comment comment1 = new Comment
            {
                Url = "https://#",
                Description = "Bla bla bla",
                Count = 1
            };
            Comment comment2 = new Comment
            {
                Url = "https://#",
                Description = "Bla bla bla",
                Count = 4
            };
            Rating rating1 = new Rating
            {
                Percent = 98,
                Count = 1
            };
            Rating rating2 = new Rating
            {
                Percent = 95,
                Count = 5
            };
            Post FormsInVanilla = new Post
            {
                Id = 1,
                Title = "Building Better HTML Forms in Vanilla-JS",
                Description = "Creating forms is one of the most basic skills for a web developer...",
                Date = DateTime.Today,
                Url = "https://www.red-gate.com/simple-talk/dotnet/net-development/building-better-html-forms-in-vanilla-js/",
                Author = DinoEsposito,
                Comments = new List<Comment>() { comment1 },
                Rating = rating1,
                Categories = new string[] { ".NET Development" }
            };
            Post VoiceCommands = new Post
            {
                Id = 2,
                Title = "Voice Commands in Unity",
                Description = "Today, we use voice in many ways. We can order groceries...",
                Date = DateTime.Today,
                Url = "https://www.red-gate.com/simple-talk/dotnet/c-programming/voice-commands-in-unity/",
                Author = LanceTalbert,
                Comments = new List<Comment>() { comment2 },
                Rating = rating2,
                Categories = new string[] { "C# programming" }
            };
            posts.Add(FormsInVanilla);
            posts.Add(VoiceCommands);
            SocialNetwork sn1 = new SocialNetwork()
            {
                Type = SNType.INSTAGRAM,
                Author = DinoEsposito,
                NickName = "@dino",
                Url = "https://#"
            };
            SocialNetwork sn2 = new SocialNetwork()
            {
                Type = SNType.TWITTER,
                Author = DinoEsposito,
                NickName = "@dino",
                Url = "https://#"
            };
            sns.Add(sn1);
            sns.Add(sn2);
        }
        public List<Author> GetAllAuthors()
        {
            return this.authors;
        }
        public Author GetAuthorById(int id)
        {
            return authors.Where(author => author.Id == id).FirstOrDefault<Author>();
        }
        public List<Post> GetPostsByAuthor(int id)
        {
            return posts.Where(post => post.Author.Id == id).ToList<Post>();
        }
        public List<SocialNetwork> GetSNsByAuthor(int id)
        {
            return sns.Where(sn => sn.Author.Id == id).ToList<SocialNetwork>();
        }
    }
}

This is mostly boilerplate code. It spends some time to create data and feed the lists necessary to handle the main operations of getting them and sending back to the clients. Feel free to add as much data as you want to make the example even more real, or even connect to a different data source.

The get methods were built in a way to simulate the REST operations of getting each resource through a different endpoint plus the identifier of its parent.

Last, but not least, create the controller class (for the REST example) that will provide each endpoint pointed out before. Inside the Controllers folder, add the following controller class:

using GraphQL_SimpleTalk.Services;
using Microsoft.AspNetCore.Mvc;
namespace GraphQL_SimpleTalk.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorsController : ControllerBase
    {
        private readonly BlogService blogService;
        public AuthorsController(BlogService blogService)
        {
            this.blogService = blogService;
        }
        [HttpGet]
        public IActionResult GetAll()
        {
            return new ObjectResult(blogService.GetAllAuthors());
        }
        [HttpGet("{id}")]
        public IActionResult GetAuthorById(int id)
        {
            return new ObjectResult(blogService.GetAuthorById(id));
        }
        [HttpGet("{id}/posts")]
        public IActionResult GetPostsByAuthor(int id)
        {
            return new ObjectResult(blogService.GetPostsByAuthor(id));
        }
        [HttpGet("{id}/socials")]
        public IActionResult GetSocialsByAuthor(int id)
        {
            return new ObjectResult(blogService.GetSNsByAuthor(id));
        }
    }
}

Note how simple it is — if you’re used to dealing with REST APIs in ASP.NET, of course. The code is basically encapsulating the BlogService service to access its operations for every endpoint. For now, the code is handling only GET HTTP operations.

That’s pretty much everything we need to run the example. But, before testing, don’t forget to add the scoped declaration of the BlogService service to the Startup class, inside the ConfigureServices() method:

services.AddScoped<BlogService>();

And you also need to import the respective class:

using GraphQL_SimpleTalk.Services;

Now, start the server, go to your web browser and test each of the endpoints. Note that you may have a different port than shown here:

It seems simple, doesn’t it? What happens when you scale this conversational design to millions, billions of requests/responses per day?

Now to see how GraphQL addresses the same scenario.

The GraphQL Approach

Initially, set the GraphiQL up. GraphiQL (a NuGet dependency you’ve already installed) is an in-browser IDE for exploring GraphQL. It saves a lot of effort when testing GraphQL services by providing syntax highlighting, smart types, fields and query autocompletion tools, real-time error reporting and query inspecting.

Again, in the Startup class, make the following changes:

public const string GraphQlPath = "/graphql";
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
    app.UseGraphiQl(GraphQlPath);
}

Again, make sure to import the proper class at the beginning of the Startup class:

using GraphiQl;

This will define in what endpoint GraphiQL UI will be available.

Secondly, in order for this path be recognized as the official ruler of all GraphQL requests, you need to create a controller to manage the schema, variables and arguments. So, create the following class inside the Controllers folder:

using GraphQL;
namespace GraphQL_SimpleTalk.Controllers
{
    public class GraphQlQuery
    {
        public string OperationName { get; set; }
        public string NamedQuery { get; set; }
        public string Query { get; set; }
        public Inputs Variables { get; set; }
    }
}

This represents what a GraphQL query is. It’s kind of a limitation of the library still, since they hadn’t included this inside the graphql-dotnet. Then, create the following controller to handle all the operations:

using GraphQL;
using GraphQL.Types;
using GraphQL_SimpleTalk.Queries;
using GraphQL_SimpleTalk.Services;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace GraphQL_SimpleTalk.Controllers
{
    [Route(Startup.GraphQlPath)]
    public class GraphQlController : Controller
    {
        readonly BlogService blogService;
        public GraphQlController(BlogService blogService)
        {
            this.blogService = blogService;
        }
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] GraphQlQuery query)
        {
            var schema = new Schema { Query = new AuthorQuery(blogService) };
            var result = await new DocumentExecuter().ExecuteAsync(x =>
            {
                x.Schema = schema;
                x.Query = query.Query;
                x.Inputs = query.Variables;
            });
            if (result.Errors?.Count > 0)
            {
                return BadRequest();
            }
            return Ok(result);
        }
    }
}

This post method is important to summarize all the GraphQL schemas of your application in one place. Here, you have already referenced the AuthorQuery object, even though it doesn’t exist yet. The DocumentExecuter is responsible for the GraphQL query execution, sending the schema, the query itself and the variables as arguments.

Now, you must define what type of objects you’re going to query. This example gets each of the author’s data, the main query will be AuthorQuery. This will be the place to store each REST endpoint respective as a same-query operation.

To understand it better, take a look at how the final GraphQL query will look (the same we’ll use to test things in GraphiQL) :

query GetBlogData($id: Int!) {
  author(id: $id) {
    id
    name
  }
  posts(id: $id) {
    author {
      bio
    }
    categories
    comments {
      description
      count
      url
    }
  }
  socials(id: $id) {
    nickName
    type
  }
}

The first thing to notice is the parameter this query requires: the author’s id. It is going to be used for each individual operation (author, posts and socials ones) as a query argument (yes, GraphQL also allows sending arguments) that’ll define which records will be returned.

The “!” sign says that this parameter is required, otherwise the query won’t work.

Lastly, see that you’re only fetching the data from each object, to demonstrate that with GraphQL, you are the owner of the server’s responses, that is, you only get what you really want.

In graphql-dotnet, each query field (in this case: author, posts and socials) must be represented as a GraphQL.Types.ObjectGraphType in order to encapsulate each subfield definitions. Start with the AuthorType by creating the class in a new Queries\Types folder:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class AuthorType : ObjectGraphType<Author>
    {
        public AuthorType()
        {
            Field(x => x.Id).Description("Id of an author");
            Field(x => x.Name).Description("Name of an author");
            Field(x => x.Bio).Description("Bio description of an author");
            Field(x => x.ImgUrl).Description("Url of an author's profile picture");
            Field(x => x.ProfileUrl).Description("Link of an author's profile");
        }
    }
}

The ObjectGraphType must receive a generic argument of the class this GraphType will configure. It’s strictly necessary that you define here each one you want to be exposed by the GraphQL query mechanism. You’re also setting the description in this type for you to notice how it appears in the final documentation in the GraphiQL interface.

It’s important to notice that for all the primitive types (string, int, etc.), you don’t need to do anything other than referencing the field at Field ‘s method. For types that you have created, you’re obligated to say which ObjectGraphType is the one managing this specific subtype. Just like you see in the next SocialNetworkType:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class SocialNetworkType : ObjectGraphType<SocialNetwork>
    {
        public SocialNetworkType()
        {
            Field(x => x.NickName);
            Field<EnumerationGraphType<SNType>>("type");
            Field(x => x.Url);
            Field<AuthorType>("author");
        }
    }
}

It’s the same connotation and syntax, except for the SNType type (it will be created in the sequence). The EnumerationGraphType represents the default GraphType handler for enums in graphql-dotnet. The generic class must be provided subsequently along with the exact type name as a string. When it comes to the types, like the author, the AuthorType itself is enough.

Add the rest of the types.

The SNTypeType class:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class SNTypeType : EnumerationGraphType<SNType>
    {
        public SNTypeType()
        {
            Name = "SNTypeType";
        }
    }
}

The CommentType class:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class CommentType : ObjectGraphType<Comment>
    {
        public CommentType()
        {
            Field(x => x.Count);
            Field(x => x.Description);
            Field(x => x.Url);
        }
    }
}

The RatingType class:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class RatingType : ObjectGraphType<Rating>
    {
        public RatingType()
        {
            Field(x => x.Count);
            Field(x => x.Percent);
        }
    }
}

The PostType class:

using GraphQL.Types;
using GraphQL_SimpleTalk.Entities;
namespace GraphQL_SimpleTalk.Queries.Types
{
    public class PostType : ObjectGraphType<Post>
    {
        public PostType()
        {
            Field(x => x.Id);
            Field(x => x.Title);
            Field(x => x.Url);
            Field(x => x.Date);
            Field(x => x.Description);
            Field<AuthorType>("author");
            Field<RatingType>("rating");
            Field<ListGraphType<CommentType>>("comments");
            Field(x => x.Categories, nullable: true);
        }
    }
}

For lists and arrays, in addition, you must use ListGraphType as the default handler. Notice, too, that the Categories field was defined as non-nullable, another possible config you’re going to use for testing.

Finally, create the AuthorQuery in the Queries folder. Even being an ObjectGraphType too, this object is the most important one, since is here where the schema is defined, as well as the resolvers you’ve seen before. There will be three fields: author, posts, and socials; each of them going through a different service method (which could possibly be another remote microservice, lambda or even data source) to fetch the data. See below the code:

using GraphQL.Types;
using GraphQL_SimpleTalk.Services;
using GraphQL_SimpleTalk.Queries.Types;
namespace GraphQL_SimpleTalk.Queries
{
    public class AuthorQuery : ObjectGraphType
    {
        public AuthorQuery(BlogService blogService)
        {
            Field<AuthorType>(
                name: "author",
                arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id" }),
                resolve: context =>
                {
                    var id = context.GetArgument<int>("id");
                    return blogService.GetAuthorById(id);
                }
            );
            Field<ListGraphType<PostType>>(
                name: "posts",
                arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id" }),
                resolve: context =>
                {
                    var id = context.GetArgument<int>("id");
                    return blogService.GetPostsByAuthor(id);
                }
            );
            Field<ListGraphType<SocialNetworkType>>(
                name: "socials",
                arguments: new QueryArguments(new QueryArgument<IntGraphType> { Name = "id" }),
                resolve: context =>
                {
                    var id = context.GetArgument<int>("id");
                    return blogService.GetSNsByAuthor(id);
                }
            );
        }
    }
}

The first important impression is the new arguments field defining a new QueryArguments for the id of an author represented as an IntGraphType.

The code snippet var id = context.GetArgument<int>("id"); is responsible for retrieving this argument based on its previous definition. The rest are just simple service calls. Also, notice that for each different type of return, the right type of the field must be outlined (e.g. ListGraphType).

It’s up to you determine if the posts and socials come directly within the author. This way, you’d implement all the searches inside of author‘s resolve parameter, however, you’d also have to have the proper attributes into the Author entity and AuthorType graph type.

GraphiQL

Time to test it! Start up the application again and access the URL: https://localhost:44360/graphql. This is the screen that’ll appear:

  1. The querying tool. In this box, you can type your GraphQL queries and it’ll give hints about the schema, autocomplete (“Ctrl + Escape” to trigger it), and validate the syntax;
  2. Button to run the queries;
  3. Button to prettify the code, indent;
  4. When clicked, show a side box with all the history of queries, even if you turn off the application;
  5. The box to add the query variables. They’re useful when you need to parameterize the query itself with data that comes from unknown sources;
  6. Documentation explorer. Here, you can search for query objects, its fields, arguments, types, nullability, etc.

The last item deserves a bit more of attention because it can be truly helpful when you’re accessing a GraphQL schema that you no nothing about. Have a look at the following screens:

It represents the navigation upon the AuthorQuery schema. You can see docs from the list of root types (the available queries), each type’s fields (ant their respective declarations), to the arguments and even GraphQL inner types.

In the third screen, specifically, if you click in AuthorType type, you’ll see the following screen:

Those are the descriptions you’ve previously set at the AuthorType class. So, go ahead and customize your docs.

To see how this works, add this query to the Query window:

query GetBlogData($id: Int!) {
  author(id: $id) {
    id
    name
  }
  posts(id: $id) {
    author {
      bio
    }
    categories
    comments {
      description
      count
      url
    }
  }
  socials(id: $id) {
    nickName
    type
  }
}

You must also add the Query Variable:

{
    "id":1
}

Click the run button to try it out:

That’s the same query pointed out before. The only new thing here is the query variable id that’s passed. The results, at the right side of the screen, are pretty much everything you’ll receive from the server. If you don’t need the posts or the socials, you don’t have to add them to the query, and the resolver won’t be called just the same way.

The input variables for the query don’t have to be, necessarily, primitive values. You can specify another type to the schema, like AuthorType, and ask the clients to send a full filled author to register in your application, for example. This communication can happen with either action method, whether it is a single GET or a registration POST like you have in REST.

Summary

This article covered the main basics regarding GraphQL services exposure in ASP.NET applications. GraphQL is highly flexible and data-driven, which means that you can now focus you client development in the exact data you want to receive from the server, i.e., you’re the owner of the data you want to get.

In order to improve your skills, in addition to the official graphql-dotnet docs, graphql-dotnet also provides some sample projects with more configurations. Obviously, you can count on the official Facebook’s GraphQL specification as well as the howtographql.com popular learning courses arranged by and to the community. Best of studies!

 

The post Getting Started with GraphQL in ASP.NET appeared first on Simple Talk.



from Simple Talk http://bit.ly/2LYrhjP
via

Monday, January 7, 2019

Better Code Reviews with GIT

Code reviews are a huge factor in improving code quality. You can find this supported in Karl Wiegers Humanizing Peer Reviews and in Steve McConnell’s Code Complete, to name just a couple well-known sources. But how you approach a code review can mean a vast difference in its effectiveness. This article shares some tips and techniques to help you make your code reviews as effective as possible: in short getting you better feedback with less net effort.

In my earlier 4-part series, The Zen of Code Reviews, I discussed general principles and practices of code reviews, but focused on Team Foundation Server (now known as Azure DevOps Server) because that is what my team was embroiled in. Fast forward a couple years later to today–new company, new team, new environment–now heavily weighted in Git and GitHub. So this time around, I want to share some new “tips from the trenches”, revisit some prior ideas, and generally expound upon things from the Git perspective, showing you simple ideas that can improve your code quality. Since this article is focused on Git, I will primarily use Git’s term—pull request or PR for short—to refer to code reviews.

Why do you want your code reviewed? So you can get feedback from your peers on inefficient, inaccurate, invalid, inexplicable, insufficient, or otherwise sub-optimal areas of your code and then make improvements. In order to do that, your job as the author of a code review is to present your case as clearly as possible. A reviewer’s job, on the other hand, is to be able to provide useful feedback, which means that the reviewer must understand the issue that your code addresses, then peruse your changes (whether really relevant to the issue at hand or not), and finally figure out what your changes mean in context, i.e. the ramifications of those changes. As the author, you have an unfair advantage. You already know the issue that your code addresses. You know which changes are significant and which are just noise. You know most (or sometimes all) the ramifications of your changes. So why not share that valuable insight with your code reviewers?

What do I mean? In its most basic form: explain yourself. Help your reviewers help you; enlighten them on anything that is less than obvious. In doing that, you also cover the other side of the coin that is just as important: justify yourself. You are making changes to your company’s crown jewels–the code that powers your website, drives your equipment, manages your processes… whatever it may be, you need to be able to show that you have clear and useful reasons for the changes you want to make.

In Zen, part 1, I described three types of comments that all play a part in helping you explain yourself: in-code comments, code-review description, and pre-review comments. With Git, I am renaming code-review description to PR preamble and I am adding a new, fourth item to that list that is a variant of pre-review comments, but deserves to be called out separately: commit comments. The four types are summarized in this table and then explained further. These are listed in the order they would typically be used.

Type

Details

When to Use

In-code Comments

Annotate your code to explain obscure, tricky, and otherwise non-obvious bits.

Before creating your pull request, during development

Commit Comments

Break your development up into mini-milestones; commit each milestone and add a commit message describing the milestone.

Before creating your pull request, during development

Pull Request Preamble

Detailed description of the purpose of your pull request with text and pictures including: what “done” means, how to exercise it, and more.

When creating a pull request

Pre-Review Comments

Explain non-obvious changes from the prior version to the current version.

Immediately after creating a pull request but before notifying reviewers

In-code Comments

These are your usual, garden variety comments:

  • Why does your loop start with x + 2 instead of x?
  • If you wrote a function that is a variant of the Lempel–Ziv–Welch algorithm, say so.
  • When you find a handy little function that is unfortunately not in a pluggable library, certainly go ahead and paste into your file but be sure to add a URL for where you found it.

Using in-code comments has its proponents and its detractors. In fact, it is often one of those sacred cows that gets some folks riled up, like “tabs vs. spaces”, “vim vs. emacs”, etc. I submit, however, that it gets folks riled up because they are looking at the wrong question. “Are comments good or bad?” is a meaningless question until you qualify that with what kind of comment you are talking about. Some types of comments are just evil. Some are not evil at all. Thus, it definitely depends which of the 9 types of comments you mean when you ask “Are comments good or bad?” See my article Fighting Evil in Your Code: Comments on Comments for details.

Commit Comments

This is the exciting new piece I am adding for Git users, because it is so natural to work in this fashion. In my experience, the most digestible types of pull requests are those that include multiple commits (for all but the most trivial pull request), where each commit represents a sub-task or milestone along the way towards the aggregate goal of your pull request. Think of this in terms of applying the Single Responsibility Principle to building your pull request. Instead of a single commit with a commit message that reads like this…

Implemented the boojum for the cantilevered praxis:
 * Back-end database wiring
 * Exposed API on the gateway
 * Connected to GUI and command-line front-ends
Took the liberty of refactoring some back-end unit tests as 
well to make the intent more clear.
Oh, and found a couple spelling mistakes in the related 
docs--don’t those tech writers use a spell checker?

… break that up into smaller pieces. You could easily make a case for this example to use 3 pieces (one for the boojum, one for the refactoring, and one for the spelling corrections) or perhaps 5 pieces. (You could also make a case to use separate PRs instead of just separate commits, but let’s assume that the sum of these is small enough to result in a PR that is modest in size.)

What is powerful about breaking this up into separate commits is that it makes your PR much more digestible by a reviewer. Instead of having to grasp the context of changes in 15 files at once, you might have one commit that involves 5 files, another that involves just 1 file, etc. The set of commits collectively tell a story, but each “chapter” can be read one at a time. In fact, just like you might read an actual book by first skimming through the table of contents, you can similarly begin your review of a PR by skimming through the commit messages. You should then be able to get a sense of the journey that the author went on to get from the start to the end.

Here is a simple, real-life example. Of course, you have absolutely no context, so I will supplement the image with this short description: Using TDD (test driven development), a new test is added in the first commit. The next commit does not say explicitly, but it is implementing new behavior to make that test pass, which involves hydrating some endpoints (the details of what hydration means in this context are unimportant). This hydration needs to be used in some cases but not others, so the third commit allows for that, with both the code and the tests. The final commit, labeled a ‘drive-by’ is unrelated to the PR proper, but it is a one-line change noticed during development so I added it here just to get it done. In GitHub, here are the commits in the PR:

The commit titles tell a story as you read through them. And the details of each commit provide further color to make that story more clear to the reader.

By the way, for a great guide to writing good commit messages, see Chris Beams’ How to Write a Git Commit Message.

PR Preamble

When working on GitHub and you press the button to create a pull request, you are immediately presented with a field for a title and a big empty text box for what I like to call the PR preamble. It is the starting point, the introduction, for your PR. It should include a summary of what the reader will be reviewing, details on how to exercise the code so a reviewer could prove that it works themselves, and more. You and your colleagues should agree upon a standard set of information you want all PRs to include and then store these in a PR template that pre-populates the text box when you create a new PR. See Creating a pull request template for your repository for more.

Your list of items to cover will be uniquely yours, but at a minimum I would recommend a description or summary, a definition of ‘done’ (how does one know your PR achieves its goal?), and the steps to exercise your code (how can a reader prove that your code changes do what they say?).

You should also include a checklist. The one my organization uses every day reminds the PR author to make sure that they have updated docs, added tests, run the tests, and exercised the code. I hear you scoff. But that “silly” checklist works. It substantially increases the likelihood of those “obvious” tasks getting done. I don’t have any citations to back that claim specifically for software, but there are many articles espousing the benefits of a checklist, for example, for a doctor performing a medical procedure or for a pilot readying an aircraft for takeoff. (Example: https://khn.org/news/hospital-checklist-mainbar/).

Here is an example preamble, short enough to fit in a screenshot:

Does your code touch anything in the UI? If so, include screenshots or videos. If you do include screenshots, add arrows, captions and the like to show what code has changed; there is always a lot going on in most any screen shot so, again, help the reader see what your code did.

I will often use diagrams, charts, or other images of data even when I am not working in UI-facing code, if I think it will help make my intent more clear.

Pre-review Comments

My Zen, part 1, was all about pre-review comments. That was, in fact, its title. In that article I propose that, once your PR is ready to be reviewed, you be your own first reviewer. Read through every changed line of code–not with the intent of critiquing though, rather with the intent of clarifying or explaining if something is not obvious. Pre-review comments serve a similar purpose to in-code comments; the latter also should clarify or explain the non-obvious. The important distinction, though, is that in-code comments explain things that are in the code while pre-review comments explain code that has been changed by the PR. There could certainly be overlap between the two; sometimes it is not clear cut whether a comment should be an in-code comment or a pre-review comment, in which case either will do. But consider the next example. GitHub only presents a small window of context for a given change, a couple lines before and after. In this case, just looking at that window did not seem to me to provide enough clues as to what a reviewer might be looking at, so I introduce the pre-review comment shown. In the finished code, that comment would be useless and, indeed, confusing. But here in the PR it immediately takes the guesswork out of what the reviewer is seeing.

When I wrote that previous article it was without the benefit of commit comments, described above. These add a richer dimension to tell a story, offloading a good portion of what I used to do with just pre-review comments. Commit comments make it so much simpler now to say that such-and-such is the case and applies to these specific lines in these 5 files. When I had only pre-review comments, I would have to add comments on each chunk of code in each relevant file. But these files and these chunks were interspersed with all the other things going on in the code review. So frequently you might see comments saying something like “this line is part of the change for such-and-such, described earlier”. Pre-review comments are still useful, though! They are quite helpful for notating something remarkable within a single commit. I definitely use less of them in favor of commit comments nowadays, but they still prove their value again and again.

Summary

Code reviews are vital when developing software, so understanding how to make a code review more effective and more productive is important for every developer. Besides this article, I encourage you to read my earlier 4-part series, The Zen of Code Review, with two parts devoted to authors and two parts devoted to reviewers:

 

The post Better Code Reviews with GIT appeared first on Simple Talk.



from Simple Talk http://bit.ly/2Fe1fbP
via