Agile Programming with Kanban

Summary

In this post I’m going to discuss the differences between waterfall and agile methods of programming.  Then I’m going to focus more on Kanban and what advantages and disadvantages it has in comparison to Scrum.  I will also be discussing the business case for using Kanban and how it can improve the performance of developing software and reducing waste.

Producing Software

Producing software costs money.  That is the bottom line.  The largest cost to creating software is the cost of man-hours or how much money is paid to the analysts, developers and quality people to create the software.  After the software has been written and delivered, then the primary cost becomes the operating costs.  Operating costs can break down into licensing fees for database and operating systems as well as hardware or hosting fees.  There will also be labor expenses tied up in support such as IT personnel, help-desk and training personnel.  I’m going to focus on the cost it takes to create the software.  As a seasoned software architect, my job is to analyze and design the software with an eye for reducing the cost of operating the software after it is delivered.  That is a subject for another blog post.  In this post I’m concerned about the process of creating the software with an eye toward reducing wasted time and money.

Waterfall Method

Everyone has heard of the waterfall method.  It’s the most obvious way to design and build software.  Basically a team of software analysts communicate with the customer to determine a list of features required/desired for the software to be built.  They will then turn this into a requirements document.  Once the requirements document has been agreed upon, a massive design effort is launched.  This can take months and for grand projects it can take years.  The project is designed down to the smallest detail so that it can be estimated.  Estimating the amount of man-hours it takes to perform the programming can be done by analysts or, if the developers are already working for the company performing the work, they can perform the estimation (it’s preferable to obtain estimates from the developers that will actually work on the project because then you can get buy-in).  Next, the negotiations start with the customer.  The customer will most certainly decide that they can’t afford the “magic wand”1 version of the software that they described and will begin to reduce the features to get the price down to something reasonable.

Once a contract is signed, then the specifications are thrown over the wall (figuratively) to the developers.  I’ve seen companies that use GAANT2 charts with critical paths detailing when each feature will be scheduled, but most companies just hand over the spec with the idea that developers can just divide-and-conquer.  Then months and probably years are spent developing the software.  There are usually demonstrations of what has been created to keep the customer from cancelling the project.  There is nothing worse than paying for a product and not hearing anything about the product until a year later when the whole thing is delivered.  The customer will want progress reports.  Is it on schedule?  Hopefully, for the customer’s sake, they paid a flat-rate price for the software and will not have to shell out more money if the developers cannot produce the software by the deadline indicated in the estimates.  Otherwise, more than likely, the project will come in over budget and late.

Once the developers have completed their tasks, quality can start testing the whole project.  QA should be building test scripts while the developers are creating the code.  Otherwise, there should be no QA people on the project until they are about ready to start testing.  Once the QA people have completed their tasks and the developers have fixed any bugs found, then it’s time for the release.

This is the waterfall method in a nutshell.

Problems with Waterfall

The biggest problem with the waterfall method is that it is wasteful.  Many projects get cancelled before completion and the customer is left with nothing.  If the tasks are not scheduled to ensure that sections of the software are workable, then there is no way to cut off development and deliver a working product with fewer features.  Also, if a project is cut because of cost overruns, then there is still QA work to be done.  Finally, the software analysts and designers must be paid for designing the entire project before any software is built.

Next, there are months where no software is being written.  This is the analysis, design and estimation phase.  The whole thing must be estimated before an agreement can be signed.  That means that time is burning while this whole process is going on and development doesn’t start until all of this work is completed.

Usability is difficult to perform before the software is built.  Usability is expensive to fix after the whole project is complete (designed, built and QA’d).  The best method of ensuring usability is cheap and effective is to test the usability as the software is being built.  This is not something that waterfall can accommodate without difficulty.  It would require very detailed scheduling and changes would loop back to a lot of changes in the design that has already been completed.  In practice, waterfall does not support effective usability testing.

The Agile Method

The theory behind the agile method is that the software is only roughly specified up front.  Then the most critical and important parts of the software are designed and estimated first.  Usually only a week or month’s worth of software is designed at a time.  Then the design is estimated by the developers who will start work immediately.  Once a few pieces of the software (usually called stories) are completed, they are QA’d and then deployed to a limited audience (the customer).  The customer will then review what is being demonstrated and normally they get hands-on access to test what has been created.  If the piece of software is large enough to be useful, the customer can start using the software.  A critique of the software can be fed back to the analysts to have some of the usability problems fixed in a future release.  Meanwhile the design team is working on the next specifications or stories to be put in the hopper.  At the same time the developers are working on the previously designed and estimated stories.  QA is working on the previously finished stories and the quality checked pieces are collected up for the next deployment.  This continues like a factory.

The stories need to be produced in the order that the customer demands.  So they can put off minor enhancements to the end and have working software as early as possible.  If the customer decides that they have spent enough money and the product is good enough, then they can cut off the project and walk away with a product that is usable.  This reduces waste.

Benefits over Waterfall

It’s almost obvious what the benefits are:

  • Working software is delivered right away.
  • There is a short startup time when the designers create the first stories.  The developers start working right away instead of waiting months or years to start.
  • The customer is more involved in the creation of the product.  Instant feed-back about usability problems can help fix the problem before the developers have forgotten what they’ve worked on.
  • The customer can cut off the project at any time and walk away with a functioning product.
  • The customer, theoretically, could start using their product before it is finished.
  • Re-prioritizing features is quick and easy since developers don’t just grab any story at any time.  The customer has full control on when features are developed.

Scrum vs. Kanban

There are several methods of running an agile development team, but two are near the top: Kanban and Scrum.  Scrum is a method where there is a fixed amount of time that developers will work on a set of stories.  This is called the sprint and it may last two, three or four weeks.   The sprint is usually a fixed time frame that is repeated throughout the project, and they are usually numbered.  For example: The analysts/designers will group stories into sprint 1 until they have filled two weeks worth of work for the team that will work on the software.  Then they will start to fill in sprint 2, etc.  In a Scrum, there are daily-standup meetings where the “team” discusses the progress since the previous standup.  The idea for a standup is that everyone stands and the meeting is limited to reporting progress, issues and blockers.  If a one-on-one discussion lasts more than a few minutes, it must be taken off-line because it is wasting the time of the entire team to sort out a problem that can be solved by two people.  Scrums provide an environment where the team knows what everyone else is working on for each sprint.

Stories that are completed are immediately passed on to QA during the sprint.  The QA personnel are included as part of the “team” and they attend the daily standup meetings as well.  At the end of the sprint the stories that are complete and QA’d are deployed and demonstrated to the customer who can give feed-back.  Any changes can be put into the next sprint or a future sprint.

Kanban is a bit different.  Kanban is broken down like a factory.  There are “lanes” where the stories will go when they are moved from the design phase to the deployment phase, like a pipeline.  Analysts/designers will put the stories into the backlog lane.  Once the stories are in the backlog, developers can immediately pick one story up and work on it.  The developer will move the story to their development lane.  When the story is complete, it is moved into the “To be QA’d” lane.  Then a QA person can pull a story out of that lane and put it in their “QA” lane.  After the QA person has completed their task, the story can be placed into the “To be Deployed” lane.  When enough stories are in that lane, they can be deployed to be reviewed by the customer.  Technically, each story can and should be deployed immediately.  This can be accomplished by an automated deployment system.

In the case where QA discovers a bug, the story must be moved back into the developer’s lane.  The developer must fix the bug as soon as he/she can and get it back into the “To be QA’d” lane.  There can be limits set to each lane to reduce the amount of allowed work in progress or WIP.  The WIP count controls the flow of stories going through the pipeline.  As you can see, Kanban is setup as a just-in-time delivery system.  The customer can literally end a project as soon as they decide they have enough features and the whole assembly line can stop without much waste in the system.  Scrum can have up to two-weeks (or three or four depending on the sprint size) worth of waste in the system when a cut-off occurs.  Keep in mind that scrum is still extremely efficient compared to waterfall and we are only splitting hairs over how much waste exists if a Kanban or Scrum project is cancelled.

Kanban

I’m going to focus on potential issues that can occur with Kanban.  First, it can be difficult to determine when a feature will be delivered.  This happens for items that are sitting in the backlog lane.  Items in the backlog can be re-prioritized until they are picked up and work begins.  Once work begins, the story must be completed (unless there is some circumstance that warrants the stoppage of work on a particular story).  If a story is at the top of the back-log an estimate of when it will get completed can only be determined when it is picked up by a developer.  Adjusting the WIP count to be low can make it easier to estimate when the story will go through the pipeline, but assumptions must be made about the timing of existing stories.  If the WIP count is high, then developers might have several stories in their lane at one time.  Now you’re probably scratching your head and thinking “why would a developer have two or more stories in their lane at a time?”  This situation usually happens when there is something that is blocking the completion of a story.  Maybe there is a question about how the story will be implemented.  The developer is waiting for an analyst to make a decision on how to proceed.  In such an instance, it is best for the developer to pickup the next story and start working on that one.  Developers are responsible for clearing their lane before picking up another story unless there is something blocking a story.  In other words, no non-blocked stories can sit in the developer’s lane.

Straight Kanban assumes that all developers are minimally qualified to work on every task.  That is not usually realistic and there are work-arounds for shops that have specialized developers.  First, Kanban can be setup with multiple backlog lanes.  Let’s pretend that your shop has back-end developers and front-end developers3.  As stories are created by analysts/designers, they can be divided and organized by front-end work vs. back-end work and placed in the appropriate backlog lane.  Back-end developers will pull stories from the back-end backlog lane and so on.  Of course there is the scheduling problem where now back-end developers must finish an API before a front-end programmer can consume the API for their interface.  This can be mitigated by breaking off a story that creates the API “shell” program with dummy data that responds to requests from the front-end.  Then the front-end developer can start consuming the API data before the back-end developer has completed the API.  Both lanes must be monitored to ensure that back-end programming lines up with front-end programming.  Otherwise, there could be situations where the front-end programmers have no API to consume and the software to be QA’d and deployed is not usable.  For Scrum, the back-end programming and front-end can be staggered in different sprints to ensure that the APIs are completed before the front-end programmers start programming.  This technique can also be used in Kanban by starting the back-end group ahead of the front-end group of programmers.

As you can tell there is usually no daily standup for Kanban.  There’s no need.  Each individual developer can meet with the person they need to in order to complete their work.  Meetings can still be held for kick-offs or for retrospectives.  I would recommend a retrospective for every project completed, Scrum or Kanban.

One last feature of Kanban that is more accommodating is the idea of throwing more resources at the problem.  When there is a team working on a problem there are multiple communication paths to consider.  Each team member must be made aware of what everyone else is working on.  In Kanban the idea is to design the stories to be independent of each other.  If a developer can focus on one story at a time, then adding a new developer to the mix is easy.  The new developer will just pickup a story and start working on it4.

Pitfalls to Watch For

Here’s a big pitfall with the agile method that must be headed off early on:  In an agile workshop the entire project is not estimated up front.  The customer wants to know what it would cost for the whole product.  In fact, most customers want a cafeteria style estimate of what every feature will cost so they can pick and choose what they want.  What the customer does not want is to pay for a month’s worth of work and then wonder how many more months it will take to get to a viable product.  It would be nice to know ahead of time how long it will take and how much it will cost.  To accommodate this, agile shops must be able to give a rough estimate of the entire project without designing the entire project.  In fact the product does not have to be designed down to the nth degree to get an estimate.  Also, an estimate on a product that is designed to the tiniest feature is not more accurate than an over-all rough estimate.  Confidence level is something that should always be taken into consideration in software design.  As projects get larger, the confidence level drops lower and lower.  The confidence level does not increase just because the product is designed down to the detail.  Don’t believe me?  Search for any large government software project that was cancelled or over-budget an you’ll discover that these projects missed their marks by 100 to 200% or more.  They are always underestimated.  Those projects are designed to the intimate detail.  The problem with software design is that there are always so many unknowns.

Create a rough design.  List the features and give a rough estimate for each feature.  Add some time to features that are really gray in definition.  Tighten your estimates for features that you know can be built in “x” amount of time.  This estimate can be used for a contract to “not exceed…” “x” amount of months or “x” amount of resources.  When the project is about to run up against the end, the customer must be made aware of the short-fall (if there is any).  Normally a shortfall will occur because a customer thinks up a feature that they need while the project is in progress.  This is additional work that can be inserted into the work-flow and preempt one of the lower priority features or the customer can agree to an extension of the project.  Sometimes a feature takes longer than the estimate and the customer should be notified of each feature that went over budget.

Customers can also be A.D.D. when it comes to deciding which stories to stuff in the backlog.  The backlog queue can churn like a cauldron of stories causing the scheduling of features to be delivered to be unknown.  If the customer is OK with the unknown delivery time, then the churn does not effect the development staff.  However, if stories are pulled out of the work lanes, then problems can start.  Shelving unfinished code can be hazardous.  Especially if a story is shelved for a month and then put back in play.  By that time the un-shelved code my not work with the current code-base and must be reworked, causing the estimate for the story to go long.

Documentation

I would recommend a wiki for the project.  The wiki should contain the design specifications and changes as they are made.  If you are using a product such as Confluence and Jira, you can use the forum feature to add questions to a story and follow up answers.  This becomes your documentation for the software.  If you add developers, they can read through the notes on what is going on and get a good idea of why the software was built the way it was built.  This documentation should be maintained as long as the software is in production.  Future development teams could use this documentation to see what ideas went into the original design.  When an enhancement is added, the notes for the enhancement should be appended to this documentation for future developers to refer to.  This documentation can also provide witness testimony for any disputes that occur between the customer and the entity developing the software.

Notes

  1. The term “Magic Wand” refers to the idea of: What would the customer want if they had a “Magic Wand” and could have every feature right now for free.
  2. GANNT charts and critical path methodology is used in physical construction projects.  Many people try to visualize software development as a “construction” project, like building a house.  Unfortunately, the methodology does not fit software design because every software project is like inventing something new, where building a house is so methodical that there are books full of estimates for each task to be performed.  GANNT charts are used for home construction, assembly line theory fits software development more accurately.
  3. A typical shop with a large number of developers will contain experts in database design, front-end advanced developers, entry-level front-end developers, back-end developers (which are usually API experts) and other specialized developers.  In such a situation scheduling can get a bit dicey, but the same work-arounds apply.
  4. In practice this technique should always work.  In the real-world there are pieces of the puzzle that are dependent on other pieces that are already completed.  A new developer will need some ramp-up time to get into the flow of what is being built.  This can also slow down existing developers who must explain what is going on.

 

 

Automated Deployment with .Net Core 2.0 Unit Tests

If you’re using an automated deployment system or continuous integration, you’ll need to get good at compiling and running your unit tests from the command line.  One of the issues I found with .Net Core was the difficulty in making xUnit work with Jenkins.  Jenkins has plug-ins for different types of unit testing modules and support for MSTest is easy to implement.  There is no plug-in that makes xUnit work in Jenkins for .Net Core 1.  There is a plug-in for nUnit that works with the xUnit output if you convert the xml tags to match what is expected by the plug-in.  That’s where this powershell script becomes necessary:

https://blog.dangl.me/archive/unit-testing-and-code-coverage-with-jenkins-and-net-core/

If you’re attempting to use .Net Core 1 projects, follow the instructions at the link to make it work properly.

For .Net Core 2.0, there is an easier solution.  There is a logger switch that allows you to output the correct xml formatted result file that can be used by the MSTest report runner in Jenkins.  You’ll need to be in the directory containing the project file for the unit tests you want to run, then execute the following:

dotnet test --logger "trx;LogFileName=mytests.trx"

Run this command for each unit test project you have in your solution and then use the MSTest runner:

This will pickup any trx files and display the familiar unit test line chart.

The dotnet-test command will run xUnit as well as MSTest so you can mix and match test projects in your solution.  Both will produce the same formatted xml output trx file for consumption by Jenkins.

One note about the powershell script provided Georg Dangl:

There are environment variables in the script that are only created when executed from Jenkins.  So you can’t test this script from outside of the Jenkins environment (unless you fake out all the variables before executing the script).  I would recommend modifying the script to convert all the $ENV variables into a parameter passed into the script.  From Jenkins the variable names would be the same as they are in the script (like $ENV:WORKSPACE), but you can pass in a workspace url to the script if you want to tests this script on your desktop.  Often times I’ll test my scripts on my desktop/laptop first to make sure the script works correctly.  Then I might test it on the Jenkins server under my user account.  After that I test from the Jenkins job itself.  Otherwise, it could take a lot of man-hours to fix a powershell script from re-running a Jenkins job just to test the script.

 

 

Deploying Software

Story

I’ve worked for a lot of different companies.  Most of them small.  Several of the companies that I have worked for have had some serious growth in their user base.  Every company I have worked for seem to follow same path from start-up to mid-sized company.  Start-ups usually staffed by amateur programmers who know how to write a small program and get it working.  Inevitably the software becomes so large that they are overwhelmed and have no clue how to solve their deployment problems.  Here are the problems that they run into:

  1. The customers become numerous and bugs are reported faster than they can fix them.
  2. Deployments become lengthy and difficult.  Usually causing outages after deployment nights.
  3. Regression testing becomes an overwhelming task.
  4. Deployments cause the system to overload.
  5. Keeping environments in-sync becomes overwhelming.

Solutions

This is where continuous integration techniques come into play.  The first problem can be tackled by making sure there is proper logging of system crashes.  If there is no log of what is going on in your production system, then you have a very big problem.

Problem number two is one that can be easy to solve if it is tackled early in the software development phase.  This problem can only be solved by ensuring everyone is on-board with the solution.  Many companies seem to double-down on manual deployments and do incredibly naive things like throwing more people at the problem.  The issue is not the labor, the issue is time.  As your software grows, it becomes more complex and takes more time to test new enhancements.  Performing a scheduled deployment at night is a bad customer experience.  The proper way to deploy production is to do it in the background.

One method of performing this task is to create new servers to deploy the software to and test the software before hooking the servers into your load-balancer.  The idea is to automate the web server creation process, install the new software on the new servers and then add them to the load-balancer with the new features turned off.  The new software needs to be setup to behave identical to the old software when the new features are not turned on.  Once the new servers are deployed, the old servers are removed from load-balancing one at a time until they have been replaced.  During this phase, the load of your servers need to be monitored (including your database servers).  If something doesn’t look right, you have the option to stop the process and roll-back.

Database changes can be the challenging part.  You’ll need to design your software to work properly with any old table, view, stored procedure designs as well as the new ones.  Once the feature has been rolled out and turned on, a future clean-up version can be rolled out (possibly with the next feature release) to remove the code that recognizes the old tables, views, stored procedures.  This can also be tested when new web servers are created and before they are added to the web farm.

Once everything has been tested and properly deployed the announcement that a new feature will be released can be made, followed by the switch-on of the new feature.  Remember, everything should be tested and deployed by the time the new feature is switched on.  If you are running a large web farm with tens of thousands (or more) of customers, you may want to do a canary release.  A canary release can be treated like a beta release, but it doesn’t have to.  You randomly choose 5% of your customers and switch on the feature on early in the day that the feature is to be released.  Give it an hour to monitor and see what happens.  If everything looks good, add another 5% or 10% of your customers.  By the time you switch on 20% of your customers you should feel confident enough to up it to 50%, then follow that by 100%.  All customers can be switched on within a 4 hour period.  This allows enough time to monitor and give a go or no-go on proceeding.  If your bug tracking logs are reporting an uptick in bugs when you switched on the first 5%, then turn it back off and analyze the issue.  Fix the problem and proceed again.

I’ve heard the complaint that canary release is like a beta program.  The first 5% are beta testing your software.  My answer to that is: If you are releasing 100% of your customers at the same time, doesn’t that mean that all your customers are beta testers?  Let’s face the facts, the choice is not between different versions of the software.  The choice is between how many people will experience the software you are releasing, 5% or 100%.  That’s why I advocate random customer selection.  The best scenario rotates the customers each release so that each customer will be in the first 5% only one it twenty releases.  That means that every customer shares the pain 1/20th of the time instead of a 100% release where every customer feels the pain every time.

Regression Testing

Regression testing is something that needs to be considered early in your software design.  Current technology provides developers with the tools to build this right into the software.  Unit testing, which I am a big advocate of, is something that needs to be done for every feature released.  The unit tests must be designed with the software and you must have adequate code coverage.  When a bug is found and reported, a unit test must be created to simulate this bug and then the bug is fixed.  This gives you regression testing ability.  It also gives a developer instant feed-back.  The faster a bug is reported, the cheaper it is to fix.

I have worked in many environments where there is a team of QA (Quality Assurance) workers who manually find bugs and report them back to the developer assigned to the enhancement causing the bug.  The problem with this work flow is that the developer is usually on to the next task and is “in-the-zone” of the next difficult coding problem.  If that developer needs to switch gears, shelve their changes, fix a bug and deploy it back to the QA environment, it causes a slowdown in the work flow.  If the developer checks in their software and the build server catches a unit test bug and reports it immediately, then that developer will still have the task in mind and be able to fix it right there.  No task switching is necessary.  Technically many unit test bugs are found locally if the developer runs the unit tests before check-in or if the system has a gated check-in that prevents bad builds from being checked in (then they are forced to fix their error before they can continue).

Load Testing

When your software becomes large and the number of customers accessing your system is large, you’ll need to perform load testing.  Load testing can be expensive, so young companies are not going to perform this task.  My experience with load testing is that it is never performed until after a load-related software deployment disaster occurs.  Then load testing seems “cheap” compared to hordes of angry customers threatening lawsuits and cancellations.  To determine when your company should start load-testing, keep an eye on your web farm and database performances.  You’ll need to keep track of your base-line performances as well as the peaks.  Over time you’ll see your server CPU and memory usage go up.  Keep yourself a large buffer to protect from a bad database query.  Eventually your customer size will get to a point where you need to load test before deployments because unpredictable customer behavior will overwhelm your servers in an unexpected manner.  Your normal load will ride around 50% one day, and then, because of year-end reporting, you wake up and all your servers are maxed out.  If it’s a web server load problem, that is easy to fix: Add more servers to the farm (keep track of what your load-balancer can handle).  If it’s a database server problem, you’re in deep trouble.  Moving a large database is not an easy task.

For database operations, you’ll need to balance your databases between server instances.  You might also need to increase memory or CPUs per instance.  If you are maxed out on the number of CPUs or memory per instance, then you are left with only one choice: Moving databases.  I could write a book on this problem alone and I’m not a full-time database person.

Environments

One issue I see is that companies grow and they build environments by hand.  This is a bad thing to do.  There are a lot of tools available to replicate servers and stand up a system automatically.  What inevitably happens is that the development, QA, staging and production environments get out of sync.  Sometimes shortcuts are taken for development and QA environments and that can cause software to perform differently that in production.  This guarantees that deployments will go poorly.  Configure environments automatically.  Refresh your environments at regular intervals.  Companies I have worked for don’t do this enough and it always causes deployment issues.  If you are able to built a web-farm with the click of a button, then you can perform this task for any environment.  By guaranteeing each environment is identical to production (except on a smaller scale), then you can find environment specific bugs early in the development phase and ensure that your software will perform as expected when it is deployed to your production environment.

Databases need to be synchronized as well.  There are tools to sync the database structure.  This task needs to be automated as much as possible.  If your development database can be synced up once a week, then you’ll be able to purge any bad data that has occurred during the week.  Developers need to alter their work-flow to account for this process.  If there are database structure changes (tables, views, functions, stored procedures, etc.) then they need to be checked into version control just like code and the automated process needs to pickup these changes and apply them after the base database is synced down.

Why spend the time to automate this process?  If your company doesn’t automate this step, you’ll end up with a database that has sat un-refreshed for years.  It might have the right changes, it might not.  The database instance becomes the wild west.  It will also become full of test data that causes your development processes to slow down.  Many developer hours will be wasted trying to “fix” an issue caused by a bad database change that was not properly rolled back.  Imagine a database where the constraints are out of sync.  Once the software is working on the development database, it will probably fail in QA.  At that point, it’s more wasted troubleshooting time.  If your QA database is out of sync?  Yes, your developers start fixing environment related issues all the way up the line until the software is deployed and crashes on the production system.  Now the development process is expensive.

Other Sources You Should Read

Educate yourself on deployment techniques early in the software design phase.  Design your software to be easy and safe to deploy.  If you can head off the beast before it becomes a nightmare, you can save yourself a lot of time and money.  Amazon has designed their system around microservices.  Their philosophy is to keep each software package small.  This makes it quick and easy to deploy.  Amazon deploys continuously at a rate that averages more than one deployment per second (50 million per year):

http://www.allthingsdistributed.com/2014/11/apollo-amazon-deployment-engine.html

Facebook uses PHP, but they have designed and built a compiler to improve the efficiency of their software by a significant margin.  Then they deploy a 1.5 gigabyte package using BitTorrent.  Facebook does daily deployments using this technique:

https://arstechnica.com/information-technology/2012/04/exclusive-a-behind-the-scenes-look-at-facebook-release-engineering/

I stumbled across this blogger who used to work for GitHub.  He has a lengthy but detailed blog post describing how to make deployments boring.  I would recommend all developers read this article and begin to understand the process of deploying software:

https://zachholman.com/posts/deploying-software

Finally…

Believe it or not, your deployment process is the largest factor determining your customer experience.  If your deployments require you to shut down your system in the wee-hours of the morning to avoid the system-wide outage from affecting customers, then you’ll find it difficult to fix bugs that might affect only a hand-full of customers.  If you can smoothly deploy a version of your software in the middle of the day, you can fix a minor bug and run the deployment process without your customers being affected at all.  Ultimately, there will be bugs.  How quickly you can fix the bugs and how smoothly you get that fix deployed will determine the customer experience.

 

 

 

Creating POCOs in .Net Core 2.0

Summary

I’ve shown how to generate POCOs (Plain Old C# Objects) using the scaffold tool for .Net Core 1 in an earlier post.  Now I’m going to show how to do it in Visual Studio 2017 with Core 2.0.

Install NuGet Packages

First, you’ll need to install the right NuGet Packages.  I prefer to use the command line because I’ve been doing this so long that my fingers type the command without me thinking about it.  If you’re not comfortable with the command line NuGet window, you can use the NuGet Package Manager Settings window under the project you want to create your POCOs in.  If you want, you can copy the commands here and paste them into the NuGet Package Manager Console window.  Follow these instructions:

  1. Create a .Net Core 2.0 library project in Visual Studio 2017.
  2. Type or copy and paste the following NuGet commands into the Nuget Package Manager Console window:
install-package Microsoft.EntityFrameworkCore.SqlServer
install-package Microsoft.EntityFrameworkCore.Tools
install-package Microsoft.EntityFrameworkCore.Tools.DotNet

If you open up your NuGet Dependencies treeview, you should see the following:

Execute the Scaffold Command

In the same package manager console window use the following command to generate your POCOs:

Scaffold-DbContext "Data Source=YOURSQLINSTANCE;Initial Catalog=DATABASENAME;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir POCODirectory

You’ll need to update the datasource and initial catalog to point to your database.  If the command executes without error, then you’ll see a directory named “POCODirectory” that contains cs files for each table in the database you just converted.  There will also be a context that contains all the model builder entity mappings.  You can use this file “as-is” or you can split the mappings into individual files.

My process consists of generating these files in a temporary project, followed by copying each table POCO that I want to use in my project.  Then I copy the model builder mappings for each table that I use in my project.

What This Does not Cover

Any views, stored procedures or functions that you want to access with Entity Framework will not show up with this tool.  You’ll still need to create the result POCO for views, stored procedures and functions by hand (or find a custom tool).  Using EF with stored procedures is not recommended.  Anyone who has to deal with legacy code and legacy database will run into a situation where they will need to interface with an existing stored procedure.

 

Using Scripts

Summary

In this post I’m going to show how you can improve developer productivity by steering developers to use scripts where it makes sense.

Setting up IIS

As a back-end developer, I spend a lot of time standing up and configuring new APIs.  One of the tools I use to reduce the amount of man-hours it takes me to get an API up and running is PowerShell.  Personally, the world “PowerShell” makes my skin crawl.  Why?  Because it’s a scripting language that has a syntax that feels like something built by Dr. Frankenstein.  To get beyond my lack of memorizing each and every syntax nuance of PowerShell, I use a lot of Google searches.  Fortunately, after several years of use, I’ve become familiar with some of the capabilities of PowerShell and I can save a lot of time when I create IIS sites.

Now you’re probably wondering where I save my time, since the script has to be written and the site only needs to be setup once.  The time saving comes when I have to change something minor or I have to establish the site on another environment.  In the case of another environment, I can change the path name or url to match the destination environment and run my script to create all the pieces necessary to run my API.

Before I get into the script, I’m going to go through the steps to create an IIS site for WebApi for .Net Core 2.0.

Step 1: Setup the Application Pool.

  • Open IIS and navigate to the Application Pool node.
  • Right-click and add.
  • Give your app pool a name that matches your site, so you can identify it quickly.  This will save you troubleshooting time.
  • For .Net Core, you need to set the .Net Framework Version to “No Managed Code”

Step 2: Setup IIS site.

  • Right-click on the “Sites” node and “Add Web Site”
  • I usually name my site the same as the URL or at least the sub-domain of the URL so I can find it quick.  Again, this name is not used by the system, it is only used when I have to troubleshoot and saving time troubleshooting is the number one priority.
  • Set the path to point to the root of your publish directory (make sure you have done a local publish from Visual Studio before performing this step).
  • Type in the host name.  This is the URL of your site.  If you are just testing locally, you can make up a URL that you’ll need to add to the Hosts file.
  • Select the Application Pool that you created earlier.

Step 3: Optional, setup Hosts file.  Use this step if you are setting up a local website for testing purposes only.

  • Navigate to C:\Windows\System32\drivers\etc
  • Edit “Hosts” file.  You might have to edit with Administrator rights.
  • Add your URL to the hosts file: “127.0.0.1       MyDotNetWebApi.com”

Now try to visualize performing this process for each environment that your company uses.  For me, that comes out to be about half a dozen environments.  In addition to this, each developer that will need your API setup on their PC will need to configure this.  Here’s where the time-saving comes in.  Create the PowerShell script first, and test the script.  Never create the site by hand.  Then use the script for each environment.  Provide the script for other developers to setup their own local copy.  This can be accomplished by posting the script on a wiki page or checking the script into your version control system with the code.

Here’s what an example PowerShell script would look like:

# if you get an error when executing this script, comment the line below to exclude the WebAdministration module
Import-Module WebAdministration

#setup all IIS sites here
$iisAppList = 
    "MyDotNetWebApi,MyDotNetWebApi.franksurl.com,c:\myapicodedirectory,", # use "v4.0" for non-core apps
    "testsite2,testsite2.franksurl.com,c:\temp,v4.0"
    


# setup the app pools and main iis websites
foreach ($appItem in $iisAppList)
{
    $temp = $appItem.split(',')
    
    $iisAppName = $temp[0]
    $iisUrl = $temp[1]
    $iisDirectoryPath = $temp[2]
    $dotNetVersion = $temp[3]
    
    #navigate to the app pools root
    cd IIS:\AppPools\

    if (!(Test-Path $iisAppName -pathType container))
    {
        #create the app pool
        $appPool = New-Item $iisAppName
        $appPool | Set-ItemProperty -Name "managedRuntimeVersion" -Value $dotNetVersion
    }
    
    
    #navigate to the sites root
    cd IIS:\Sites\
    
    if (!(Test-Path $iisAppName -pathType container))
    {
        #create the site
        $iisApp = New-Item $iisAppName -bindings @{protocol="http";bindingInformation=":80:" + $iisUrl} -physicalPath $iisDirectoryPath
        $iisApp | Set-ItemProperty -Name "applicationPool" -Value $iisAppName
        
        Write-Host $iisAppName "completed."
    }
}

c:

You can change the sites listed in the list of sites at the top of the script.  The app pool is setup first, followed by the IIS web site.  Each section will test to see if the app pool or site is already setup (in which is skips).  So you can run the PowerShell script again without causing errors.  Keep the script in a safe location, then you can add to the list and re-run the PowerShell script.  If you need to recreate your environment, you can create all sites with one script.

If you delete all your IIS sites and app pools you might run into the following error:

New-Item : Index was outside the bounds of the array.

To fix this “issue” create a temporary web site in IIS (just use a dummy name like “test”).  Run the script, then delete the dummy site and it’s app pool.  The error is caused by a bug where IIS is trying to create a new site ID.

Setting a Directory to an Application

There are time when you need to convert a directory in your website into it’s own application.  To do this in IIS, you would perform the following steps:

  • Expand the website node
  • Right-click on the directory that will be converted and select “Convert to Application”
  • Click “OK”

To perform this operation automatically in a script, add the following code after creating your IIS sites above (just before the “c:” line of code):

$iisAppList = 
    "MyDotNetWebApi,MyAppDirectory,MyAppDirectory,MyDotNetWebApi\MyAppDirectory,"

foreach ($appItem in $iisAppList)
{
    $temp = $appItem.split(',')

    $iisSiteName = $temp[0]
    $iisAppName = $temp[1]
    $iisPoolName = $temp[2]
    $iisPath = $temp[3]
    $dotNetVersion = $temp[4]

    cd IIS:\AppPools\

    if (!(Test-Path $iisPoolName -pathType container))
    {
        #create the app pool
        $appPool = New-Item $iisPoolName
        $appPool | Set-ItemProperty -Name "managedRuntimeVersion" -Value $dotNetVersion
    }

    cd IIS:\Sites\
    
    # remove and re-apply any IIS applications
    if (Get-WebApplication -Site $iisSiteName -Name $iisAppName)
    {
        Remove-WebApplication -Site $iisSiteName -Name $iisAppName
    }

    ConvertTo-WebApplication -PSPath $iisPath -ApplicationPool $iisPoolName
}

Now add any applications to the list.  The first parameter is the name of the IIS site.  The second parameter is the application name.  The third parameter is the pool name (this script will create a new pool for the application).  The fourth parameter is the path to the folder.  The last parameter is the .Net version (use v4.0 if this application is not a .Net Core project).

For the above script to run, you’ll need to create a blank directory called: C:\myapicodedirectory\MyAppDirectory

Now execute the script and notice that the MyAppDirectory has been turned into an application:

You can add as many applications to each IIS website as you need by adding to the list.

What the code above does is it creates an application pool first (if it doesn’t exist already).  Then it removes the application from the site followed by converting a directory to an application for a specific site.  This script can also be executed multiple times without causing duplicates or errors.

If you run into problems executing your script, you might have to run under an Administrator.  I usually startup powershell in Administrator mode.  Then I navigate to the directory containing the script.  Last, I execute the script.  This allows me to see any errors in the console window.  If you right-click on the ps1 file and run with powershell, your script could fail and exit before you can read the error message.

Feel free to copy the scripts from above and build your own automated installation scripts.