These are my thoughts about Dennis Doomen's post on documenting code...
I dislike comments in code. They represent a failure on the author's part to express an idea in the language they're using (C#, Java, etc.). That doesn't mean I never use them, or find them completely useless. They should be the exception not the norm.
I use the class, method, and parameter names to infer what the code will do. If I have questions using an API, I try to write some form of test which captures what I want to do. If I want to know more about the implementation details, I'll go look. I think well named components and a suite of tests do a lot more to document code. They also don't go stale. I'll also favor writing tests around my code to demonstrate how it works or what it does.
When I need to see how a library works, I'll look for code examples. The online docs, and available online resources are my resources. It's rare I'll simply use the comments on the public/protected members.
Inline comments are a real red flag to me. Way too often I see them when a dev hasn't expressed themselves well enough in the language they're using. These should be really, really, really rare. The nice thing about these being so rare is they stand out. Most of the devs I've worked with have learned that an inline comment is a danger sign that we've left for one another. They also tend to disappear as a code base matures.
Commit messages are stupid important. I don't know if I consider this documenting the code. It's more a history of what happened and why it happened. It's helpful if the commit messages focus on what the changes did: "Added login screen," or, "updated main landing screen to show user name."
There's my $.02.
Thursday, October 1, 2015
Thursday, August 13, 2015
Nancy Authentication with Owin and JWT
A huge part of this stuff is based upon blog posts by Jonathan Channon and Mike Hadlow.
It took me a bit of time to figure out all the working bits to building something atop Nancy using JWT for authentication. I decided to create an example app that could be used as a reference when I need to do this again. This isn't a tutorial. It's the descriptions of all the different moving parts.
The app has a very basic SPA, some RESTful endpoints, and basic unit tests. This particular app is setup for ASP.NET hosting (handy for hosting it in Azure).
The example app is on GitHub.
Solution Layout
The solution consists of two projects: NancyAspNetOwin.WebApp and NancyAspNetOwin.WebApp.UnitTests. The App directory contains all the files which comprise the SPA front-end. The Authentication directory houses the C# classes which support the token authentication. It also includes the Nancy Module which provides the endpoints that support authentication. Content, fonts, and Scripts all hold the plumbing bits such as Bootstrapper, KnockoutJS, etc. MyBootstrapper.cs and Startup.cs wire up the Nancy and Owin bits. index.html and IndexModule.cs are the kick off point.
Setting Things Up
There are a boat load of NuGet packages which need to be added when starting from an empty web application project. Some are the Nancy/Owin related stuff for the back-end. Others support the front-end SPA stuff. For this app, there were a few other things I dropped.
Nancy/Owin NuGet Packages:
There are two files running the show here: Startup.cs and MyBootstrapper.cs. Startup.cs has the Owin stuff. The pathsToIgnore variable contains all the routes we want exempted from the token-based security. These paths, along with an instance of the SecureTokenValidator class are passed into the RequiresStatelessAuth() method.
MyBootstrapper has two overrides. The RequestStartup() override contains the glue for the Owin stuff. The ConfigureConventions() override tells Nancy about the other directories that hold static content (JavaScript files, CSS files, etc.).
The Client UI
It took me a bit of time to figure out all the working bits to building something atop Nancy using JWT for authentication. I decided to create an example app that could be used as a reference when I need to do this again. This isn't a tutorial. It's the descriptions of all the different moving parts.
The app has a very basic SPA, some RESTful endpoints, and basic unit tests. This particular app is setup for ASP.NET hosting (handy for hosting it in Azure).
The example app is on GitHub.
Solution Layout
The solution consists of two projects: NancyAspNetOwin.WebApp and NancyAspNetOwin.WebApp.UnitTests. The App directory contains all the files which comprise the SPA front-end. The Authentication directory houses the C# classes which support the token authentication. It also includes the Nancy Module which provides the endpoints that support authentication. Content, fonts, and Scripts all hold the plumbing bits such as Bootstrapper, KnockoutJS, etc. MyBootstrapper.cs and Startup.cs wire up the Nancy and Owin bits. index.html and IndexModule.cs are the kick off point.
Setting Things Up
There are a boat load of NuGet packages which need to be added when starting from an empty web application project. Some are the Nancy/Owin related stuff for the back-end. Others support the front-end SPA stuff. For this app, there were a few other things I dropped.
Nancy/Owin NuGet Packages:
- JWT
- Microsoft.Owin
- Microsoft.Owin.Host.SystemWeb
- Nancy
- Nancy.Hosting.Aspnet
- Nancy.Owin
- OWIN
- Owin.StatelessAuth
SPA NuGet Packages:
The web.config file needs to be updated. The system.web and system.webServer sections need things for Nancy. An appSettings entry is created for the OWIN middleware.
- Bootstrap CSS
- KnockoutJS
- RequireJS
- Require.JS.Text
- login.css - Pulled from bootsnip.com.
- form.css
The web.config file needs to be updated. The system.web and system.webServer sections need things for Nancy. An appSettings entry is created for the OWIN middleware.
You'll also want to set the project to use HTTPS.
The Workflow
The flow for this app is pretty simple. A login form is displayed when first landing on the home page. When the credentials are entered, a token is retrieved from the login endpoint. This token is then used to pull the greeting from the secure endpoint.
Startup CodeThe flow for this app is pretty simple. A login form is displayed when first landing on the home page. When the credentials are entered, a token is retrieved from the login endpoint. This token is then used to pull the greeting from the secure endpoint.
There are two files running the show here: Startup.cs and MyBootstrapper.cs. Startup.cs has the Owin stuff. The pathsToIgnore variable contains all the routes we want exempted from the token-based security. These paths, along with an instance of the SecureTokenValidator class are passed into the RequiresStatelessAuth() method.
MyBootstrapper has two overrides. The RequestStartup() override contains the glue for the Owin stuff. The ConfigureConventions() override tells Nancy about the other directories that hold static content (JavaScript files, CSS files, etc.).
The Client UI
The UI implementation starts with the index.html file. Its layout was pulled from a template site. The rest of the client app is housed within the App folder. It contains the two knockout components, the config for RequireJS (config.js), and the basic application view model (myapp.js).
The index.html and myapp.js files act as the main view/view model for the app. index.html contains the markup, CSS file references, and script file references. myapp.js has the data bindings used by the app.
Each component is split into three files. These three files contain the HTML which serves as the view, the JavaScript view model, and code to register the component in Knockout.
The login component view (login-control.html) is a basic html file.
The login component view model (login-control.js) is a little more interesting. The params are come from a data binding on the index.html page. If a token is returned the page adds the token to future headers, raises an event, and hides the form. This is the spot you could store the token in a cookie or something.
The login component registration (login-control-register.js) tells Knockout what files to use to display the component. Pay attention to the template property. The use of "text!" lets RequireJS know that the file isn't a code file.
The Service Stuff
Nancy supports a number of view engines, routing definitions, etc. The NancyModule is quite capable of returning views, exposing RESTful endpoints, etc. Each module can support different authentication requirements.
IndexModule.cs is a NancyModule with two endpoints: /, and ./health. Both require an https call. /health requires that the caller supply a valid token in the request header. The RequiresAuthentication() method uses the ClaimsPrincipal data created by the SecureTokenValidator class.
The SecureTokenValidator class (lifted from here) verifies that the token provided in a request is valid. It also converts the token into the ClaimsPrincipal object used by Nancy. It's interesting to note that I've seen two variations on this class. Both have noted that the token does not directly decode to a set of claims.
Testing Notes
Nancy was designed to be very testable. There's the Nancy.Testing package goes a long way to helping with that. The Nancy documentation does a good job of explaining how to test your Nancy app. Testing Nancy with OWIN is a little more involved. You'll need the Microsoft.Owin.Testing package. OwinTests.cs in the test project gives an example of how those tests are done.
In Closing
That's all I have so far. Hopefully, this will help some other people who are trying to work through these issues.
The index.html and myapp.js files act as the main view/view model for the app. index.html contains the markup, CSS file references, and script file references. myapp.js has the data bindings used by the app.
Each component is split into three files. These three files contain the HTML which serves as the view, the JavaScript view model, and code to register the component in Knockout.
The login component view (login-control.html) is a basic html file.
The login component view model (login-control.js) is a little more interesting. The params are come from a data binding on the index.html page. If a token is returned the page adds the token to future headers, raises an event, and hides the form. This is the spot you could store the token in a cookie or something.
The login component registration (login-control-register.js) tells Knockout what files to use to display the component. Pay attention to the template property. The use of "text!" lets RequireJS know that the file isn't a code file.
The Service Stuff
Nancy supports a number of view engines, routing definitions, etc. The NancyModule is quite capable of returning views, exposing RESTful endpoints, etc. Each module can support different authentication requirements.
IndexModule.cs is a NancyModule with two endpoints: /, and ./health. Both require an https call. /health requires that the caller supply a valid token in the request header. The RequiresAuthentication() method uses the ClaimsPrincipal data created by the SecureTokenValidator class.
The SecureTokenValidator class (lifted from here) verifies that the token provided in a request is valid. It also converts the token into the ClaimsPrincipal object used by Nancy. It's interesting to note that I've seen two variations on this class. Both have noted that the token does not directly decode to a set of claims.
Testing Notes
Nancy was designed to be very testable. There's the Nancy.Testing package goes a long way to helping with that. The Nancy documentation does a good job of explaining how to test your Nancy app. Testing Nancy with OWIN is a little more involved. You'll need the Microsoft.Owin.Testing package. OwinTests.cs in the test project gives an example of how those tests are done.
In Closing
That's all I have so far. Hopefully, this will help some other people who are trying to work through these issues.
Thursday, July 9, 2015
SPA Notes
This is an outline of some stuff for weaving KnockoutJS, RequireJS, and Bootstrap into a site. I'm not saying these are best practices or anything. Just my notes on what I have been doing. Mostly geared towards SPAs.
The Setup (Config) File
Notice that the JavaScript files do not have the .js extension in the config file. The shim property is used to ensure certain load orders (Bootstrap requires jQuery). The paths can be combined when loading dependencies.
The HTML File
It still needs the css files. The data-main attribute in the scripts tag tells RequireJS to get everything from that file.
Modules
It's not necessary to have a parameter for each dependency. The above module uses a bootstrap modal function, but doesn't need a variable (lines 34 and 55).
Examples of getting and posting some json are at lines 24 and 48. I use the $.ajax at 48, because it lets me specify the contentType. I ran into problems using $.post.
More to come on this...
It's not necessary to have a parameter for each dependency. The above module uses a bootstrap modal function, but doesn't need a variable (lines 34 and 55).
Examples of getting and posting some json are at lines 24 and 48. I use the $.ajax at 48, because it lets me specify the contentType. I ran into problems using $.post.
More to come on this...
Thursday, June 4, 2015
TDD Resources
This is a quick and dirty post listing some (imho) good resources for TDD.
Definitions
Books
Definitions
- Unit Test - A test which verifies a unit of work. There must not be any interaction with external resources (databases, file systems, etc.). May or may not test more than one component or class.
- Integration Test - A test which verifies a unit of work. These tests interact with external resources (databases, file systems, etc.).
Books
Blog Posts
- String Calculator Kata - A daily exercise.
- Unit Test Samples - Some quick examples I made.
- Top 5 TDD Mistakes
- Context Specification
Videos
Tools
Wednesday, May 20, 2015
NancyFX Notes: Static Content
NancyFX Notes
This is part of a set of articles that are my developer notes for working with Nancy. Taken from the Nancy introduction, "Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono." It's (she's?) great for building microservices and other things.
Static Content
Static content are files like images, JavaScript files, css files, etc. Nancy automatically supports static files which are placed in the Content directory. The example on GitHub has custom directories for the 3rd-party scripts and the application-specific scripts. These are Scripts and App directories.
Other directories can be included by adding to NancyConventions.StaticContentConventions property. Do this by overriding the ConfigureConventions method in your bootstrapper.
The shot from Fiddler below shows a before and after. The calls from 5-8 were made before the additions to the bootstrapper. The later calls show that the changes enabled Nancy hosting the files in those directories.
This is part of a set of articles that are my developer notes for working with Nancy. Taken from the Nancy introduction, "Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono." It's (she's?) great for building microservices and other things.
Static Content
Static content are files like images, JavaScript files, css files, etc. Nancy automatically supports static files which are placed in the Content directory. The example on GitHub has custom directories for the 3rd-party scripts and the application-specific scripts. These are Scripts and App directories.
Other directories can be included by adding to NancyConventions.StaticContentConventions property. Do this by overriding the ConfigureConventions method in your bootstrapper.
The shot from Fiddler below shows a before and after. The calls from 5-8 were made before the additions to the bootstrapper. The later calls show that the changes enabled Nancy hosting the files in those directories.
Wednesday, November 19, 2014
Continuous Deployment Notes
Preface
Continuous integration and deployment are important concepts in efficiently delivering products. Here's some notes I've made about setting up a continuous deployment pipeline using TFS, TeamCity, and Octopus Deploy. It's a work in progress, but I hope it will help someone else out there.
The Process
The process is pretty simple. Code is checked into source control. A build server picks up the changes. It uses a build script to create a .nupkg file containing the build artifacts. This .nupkg file is uploaded to an Octopus-hosted NuGet repository. Octopus is then used to deploy the artifacts to a target environment.
The Build Server
Here's some details on the build server. It is a Server 2008 R2 machine with SP1. It's got .NET 4.5.1, Visual Studio and TeamCity installed. Some things were dropped into a 'Tools' directory on the main drive: MsBuildTasks, a custom Regex task, NuGet, NUnit, and Octo.exe.
The Sample Project
I'll be using a small, sample project illustrate where things go, and how they are used. The project structure, as it is checked into source control is similar to the following:
The Project File
The sample project uses the SampleProject.proj file to define the steps necessary for building the solution. Using a project file allows us to have a (mostly) product independent build sequence. All the major steps for creating a product artifact are codified in the project file. Be sure to check out the project file documentation on MSDN's site.
Yes, it could use some cleanup, but this is what's running now. It was originally designed to work with either Jenkins or TeamCity. It's being updated to work only with TeamCity.
Why use a file instead of setting the steps up in TeamCity? With the exception of the NUnitTeamCity addin, the script can be used in Jenkins. That means you can pick this file up and go with whatever CI server you want. I'm hoping to post something about that later. It's also easier for me to visualize the build process in one file, versus the million option pages that is TeamCity.
Continuous integration and deployment are important concepts in efficiently delivering products. Here's some notes I've made about setting up a continuous deployment pipeline using TFS, TeamCity, and Octopus Deploy. It's a work in progress, but I hope it will help someone else out there.
The Process
The process is pretty simple. Code is checked into source control. A build server picks up the changes. It uses a build script to create a .nupkg file containing the build artifacts. This .nupkg file is uploaded to an Octopus-hosted NuGet repository. Octopus is then used to deploy the artifacts to a target environment.
The Build Server
Here's some details on the build server. It is a Server 2008 R2 machine with SP1. It's got .NET 4.5.1, Visual Studio and TeamCity installed. Some things were dropped into a 'Tools' directory on the main drive: MsBuildTasks, a custom Regex task, NuGet, NUnit, and Octo.exe.
The Sample Project
I'll be using a small, sample project illustrate where things go, and how they are used. The project structure, as it is checked into source control is similar to the following:
./SampleProject/ SampleProject.proj src/ SampleProject.sln Version.cs SampleProject.Host/ SampleProject.Library/ SampleProject.Library.UnitTests/
The Project File
The sample project uses the SampleProject.proj file to define the steps necessary for building the solution. Using a project file allows us to have a (mostly) product independent build sequence. All the major steps for creating a product artifact are codified in the project file. Be sure to check out the project file documentation on MSDN's site.
Yes, it could use some cleanup, but this is what's running now. It was originally designed to work with either Jenkins or TeamCity. It's being updated to work only with TeamCity.
Why use a file instead of setting the steps up in TeamCity? With the exception of the NUnitTeamCity addin, the script can be used in Jenkins. That means you can pick this file up and go with whatever CI server you want. I'm hoping to post something about that later. It's also easier for me to visualize the build process in one file, versus the million option pages that is TeamCity.
Versioning
Mike Hadlow has a pretty nifty trick for assembly versions in a solution. It uses one file to set the version information for all the artifacts in a solution. His blog post explains it. I'm a big fan of Semantic Versions. Using the one-file trick really eases process of maintaining the changes to the version numbers.
Using the one-file trick, it became possible to use a regex task to update the file. This made it possible to have the version number based on the TeamCity build number. A co-worker found the build task, so I'm not sure where it originally came from. This custom task is also added to the Build Server's tools directory.
Using the one-file trick, it became possible to use a regex task to update the file. This made it possible to have the version number based on the TeamCity build number. A co-worker found the build task, so I'm not sure where it originally came from. This custom task is also added to the Build Server's tools directory.
TeamCity
The bummer about TeamCity is the clicky-ness of the interface. There are roughly a million different links, each leading to a new page. Each page has a dozen or so things you can set. Sure, it's amazingly powerful and flexible. But, it's easy to get lost. This isn't a knock on TeamCity. I'm just easily confused.
The first thing to set in TeamCity is the build number format. This is accessible on the first page of the build configuration settings.
Note: The format of the variable changes when used in a MSBuild file. In the project file, the any '.' in the variable name must be replaced with an '_'. That means 'build.number' becomes 'build_number'.
Octopus
Using Octopus to deploy is a straightforward process: create an environment, add some machines, create a release. Installing Octopus and tentacles on target machines is covered in the Octopus online documentation.
The first step is to create an environment. Once the environment is setup with machines, a project is needed. Finally, a release is created to actually deploy the artifacts. Once the environment is setup, you can perform your deployment as normal.
Octopus is pretty flexible in terms of the scripting and other custom install actions. The sample project is a TopShelf service. Installing and uninstalling it just needs a couple custom actions around the deploy action.
-
Wrapping It Up
Hopefully this will help someone resolve some of the issues with setting up a CI build process.
-
The scripts can be as simple as, C:\Services\SampleProject\SampleProject.Host.exe uninstall.
Wrapping It Up
Hopefully this will help someone resolve some of the issues with setting up a CI build process.
Thursday, October 9, 2014
Toggling With Windsor
Preface
There are a number of times when we've all had to implement new features or modify the implementation of an existing code base. An intern recently asked me how to feature toggle something using Castle.Windsor. This post will show how to use some Castle.Windsor features to toggle implementations. The example code can be found on GitHub.
Primitive Dependencies
The toggle will be an app setting in the application's config file. It will be loaded by Castle.Windsor by using a custom dependency resolver. This resolver is taken from Mark Seeman's post on AppSettings.
The Service
We'll be using a simple interface as our service definition. There will be two implementations. One represents an old implementation, the other a new.
It's useful to note that this is a common way to achieve some branching by abstraction. This is done by replacing calls to a service with an interface. This interface is the abstraction. Once the calls to the old service are replaced, you are free to implement a new service. When ready, the new service can be substituted for the old without the consumers being aware since they depend on the interface not the concrete.
Typed Factory Selector
Castle.Windsor comes with a handy little bit: the typed factory facility. The typed factory facility lets Castle.Windsor create a factory implementation from an interface defined by you. This relieves you of the task of implementing the factory on your own. It is especially useful if you want to defer the creation of the object.
Our class will use this factory to get an instance of our service, and call the .Print() method. The default for this object will be the first one registered in the container. This behavior can be overridden by implementing a custom selector.
The typed factory and selector must both be registered with the container. The selector must also be specified in the configuration of the typed factory. This is done on lines 21 and 22 of the ContainerFactory class.
Using IHandlerSelector
Mike Hadlow provides a very good example of using a custom IHandlerSelector.
We can use a similar technique to pull in a config value and supply the appropriate implementation at run time. The custom IHandlerSelector uses the config value to select the appropriate handler. If no handlers are found it throws an exception. This handler is then returned.
This service handler must be registered and added to the container's kernel. Line 19 of the ContainerFactory class show the registration. Line 26 shows the selector being added to the kernel. While there is only one selector in this example, the snippet shows how to add more than one.
Running the Console
Changing the config value and running the console app shows that the selectors are functioning correctly.
Wrapping It Up
Feature toggles and branching by abstraction are powerful ways to control whether new code is being used in production. They provide a way to replace old behavior with new, while maintaining the integrity of the product's build. Hopefully these two examples will help you integrate feature toggling into your builds.
There are a number of times when we've all had to implement new features or modify the implementation of an existing code base. An intern recently asked me how to feature toggle something using Castle.Windsor. This post will show how to use some Castle.Windsor features to toggle implementations. The example code can be found on GitHub.
Primitive Dependencies
The toggle will be an app setting in the application's config file. It will be loaded by Castle.Windsor by using a custom dependency resolver. This resolver is taken from Mark Seeman's post on AppSettings.
The Service
We'll be using a simple interface as our service definition. There will be two implementations. One represents an old implementation, the other a new.
It's useful to note that this is a common way to achieve some branching by abstraction. This is done by replacing calls to a service with an interface. This interface is the abstraction. Once the calls to the old service are replaced, you are free to implement a new service. When ready, the new service can be substituted for the old without the consumers being aware since they depend on the interface not the concrete.
Typed Factory Selector
Castle.Windsor comes with a handy little bit: the typed factory facility. The typed factory facility lets Castle.Windsor create a factory implementation from an interface defined by you. This relieves you of the task of implementing the factory on your own. It is especially useful if you want to defer the creation of the object.
Our class will use this factory to get an instance of our service, and call the .Print() method. The default for this object will be the first one registered in the container. This behavior can be overridden by implementing a custom selector.
The typed factory and selector must both be registered with the container. The selector must also be specified in the configuration of the typed factory. This is done on lines 21 and 22 of the ContainerFactory class.
Using IHandlerSelector
Mike Hadlow provides a very good example of using a custom IHandlerSelector.
We can use a similar technique to pull in a config value and supply the appropriate implementation at run time. The custom IHandlerSelector uses the config value to select the appropriate handler. If no handlers are found it throws an exception. This handler is then returned.
This service handler must be registered and added to the container's kernel. Line 19 of the ContainerFactory class show the registration. Line 26 shows the selector being added to the kernel. While there is only one selector in this example, the snippet shows how to add more than one.
Running the Console
Changing the config value and running the console app shows that the selectors are functioning correctly.
Wrapping It Up
Feature toggles and branching by abstraction are powerful ways to control whether new code is being used in production. They provide a way to replace old behavior with new, while maintaining the integrity of the product's build. Hopefully these two examples will help you integrate feature toggling into your builds.
Subscribe to:
Posts (Atom)







