Micro-Services, Eventual Consistency and Event sourcing patterns
 

Microservices is a really becoming a famous architectural pattern that most of the new software written these days, just apply them. One of the most important differentiation between the traditional web services and micro services pattern is the amount of common stuff across different subject areas. This calls for a discussion on how Eventual Consistency pattern is mandatory for successfully implementing micro services.

Micro-Service Pattern

Generally in a micro-service pattern, the API’s are split in to small subject areas. For example for a CRM application, the subject areas are

  • Customer information – like name, address, email, phone
  • Appointment information – which customer, sales person, when, where
  • Relationship management – sales/manager, what products, interests
  • Campaign data – offers, deals etc

Then micro-services are built for each of the subject areas.  The microservices are logically and physically separated from each other. ie there is no sharing (code, database, component etc) between any of these micro services of these subject areas. Pictorially its looks something like this.

Applying Eventual Consistency Pattern

In Micro-services, there is no data that is shared across the micro services. In order to synchronize the data across these isolated storages of these services, we need to apply the eventual consistency pattern. You can read more about applying the pattern correctly here. The simpler way we can achieve consistency across these micro-services is through Event Sourcing pattern.

Event Sourcing

Event sourcing is a process of capturing application state changes in the form of events.  An example of events are customer created, customer updated, Deal created, etc.  Other systems listen to these events and they take relevant action. You can read more about event sourcing here.

Conclusion

Event sourcing is the new way of storing changes to systems and help in making micro-services eventually consistent. These patterns together form well maintainable, reliable and scalable systems in the modern world.

BDD (Behavior Driven Development)
 

In the previous article we looked at how to do Test Driven Development (TDD) while doing the XP (Extreme Programming). In XP, the implementation of the tasks are done in the steering phase of the iteration planning. One of the tenets of the steering phase is “functional tests are run”. In this article we will see how to create functional tests using Behavior driven development (BDD) and its benefits.

Following are the some of the benefits of automated functional tests.

  • Functionality experienced by the User is tested
  • Saves testing time for the developers
  • Test in every environment (Dev, QA, Stage) without much effort
  • Generates confidence in every stake holder

Tools required for doing BDD in .Net

There are various tools available to do BDD in .Net. I have listed few of them below

SpecFlow is one of the most popular tools used in the .Net/C# community. And in this blog lets use the same. The tool comes as a Visual Studio Extension and can be downloaded directly from VS.

Creating a SpecFlow Project

Once SpecFlow extension is installed, the template required for doing BDD will be installed.

  • Create a simple “Class Library” Project in Visual studio
  • In the project, create a SpecFlow Feature file

Selecting the test framework

Before we Create/execute the scenario, we need to wire the SpecFlow with a compatible test framework. To do that we need to make changes to the app.Config file of the project.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
  <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
    <unitTestProvider name="xUnit" />
  </specFlow>
</configuration>

In this example we are using XUnit as the testing framework. SpecFlow supports a series of testing frameworks and more details can be found here.

Creating the Behavior

Now, let us look at how to create a functional test using behavior driven approach. Let’s consider the following story while creating a POS (point of sale) application for a super market.

“As a Supermarket POS app developer,  i would like the API to Give the total amount while billing so that I can wire up API against the UI.

Let’s write the Behavior required in order to implement the above API requirement .

Feature: SuperMarketProductsAPI
	As a Supermarket Biller 
	i would like the API to
	Give the total amount while billing
@SmokeTest
Scenario: Find the total amount while billing
	Given Shopping cart is filled with all the items required by consumer
	And Campaign information for the month is available in the system
	When I pass the cart to create bill API
	Then the total bill amount should be calculated

The above specification is written using the custom language (testing DSL) create by the specflow.org. (Please read about what is DSL here.)

There are 2 parts to the above Specflow specification

  • Feature – Denotes bigger context (description/story) of the application
  • Scenario – Specific workflow or behavior of the system under the feature. Each scenario has the following sub-parts
    • Given, And – describes what we already assumed available
    • When – The specific action which will trigger the workflow/behavior
    • Then  – expected behavior

 

Creating step definitions

When we run the unit test corresponding to the above test we it will fail as there are no definitions corresponding to the above scenarios.

Now Right Click on the feature file and select “Generate step Definitions”

You will see the pop-up like below, select “Generate” and then “Save” the file.

The file will have the details about “what SpecFlow should do when test is executed”.

using System;
using TechTalk.SpecFlow;

namespace SuperMarketFunctionalTests
{
    [Binding]
    public class SuperMarketProductsAPISteps
    {
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            ScenarioContext.Current.Pending();
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            ScenarioContext.Current.Pending();
        }
    }
}

When you build the project and execute the test corresponding to this, it will fail. This is because none of the parts of the test (given, when, then) are having implementation.

Writing code to make it work

Now that the behavior has been created, we are good to validate that with the team and implement the code/functionality corresponding to the requirement. Of course using best coding practices like TDD 🙂

Making the behavior test pass

In order to make the behavior test pass we need to write the implementation in the “Step Definition” file.

namespace SuperMarketFunctionalTests
{
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.Net.Http;
    using TechTalk.SpecFlow;
    using Xunit;

    [Binding]
    public class SuperMarketProductsAPISteps
    {
        Product P1 = new Product { Name = "test1", Cost = 5 };
        Product P2 = new Product { Name = "test2", Cost = 10 };
        ShoppingCart cart;
        List<Campaign> campaign;
        Bill bill;
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            cart = new ShoppingCart { Products = new List<Product> { P1, P2 } };
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            campaign = new List<Campaign> { new Campaign { product = P1, discount = 1 } };
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            var client = new HttpClient();
            var response = client.PostAsync("http://myapi.supermarket.com", new StringContent(JsonConvert.SerializeObject(cart))).Result;
            var output = response.Content.ReadAsStringAsync().Result;
            bill = JsonConvert.DeserializeObject<Bill>(output);
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            Assert.True(bill.totalAmount == 14);
        }
    }
}

Once the code is there we can see the behavior test pass.

Conclusion

BDD is very powerful way of ensuring high code quality in conjunction with business requirement. In Extreme programming (XP) , BDD is considered to be a very important practice where functional tests are mandated to run at least once during the iteration.  Is BDD/Functional tests helping your team/business in achieving success or not ? Do let us know your thoughts.

MEAN stack Part 2 – Yeoman and generator-angular-fullstack
 

This is the second post in the Getting started with MEAN series where we start looking at the Node ecosystem for stable web application frameworks for our application. A brief glance through the Express framework showed that express by itself would be time consuming start off with from scratch. On the other hand, the Express.js website links to a number of frameworks built on top of Express. This looked like a good place to start exploring.

Going through the list of frameworks mentioned there, however, we quickly noticed that a number of options were either targeted only (or primarily) towards APIs, lacked sufficient documentation for our needs, or did not appear to have a sufficiently large community behind them. Mind you, the assessment wasn’t entirely objective, as I did have previous experience with generator angular fullstack.

Why generator-angular-fullstack

Generator angular fullstack is a Yeoman generator that provides an application skeleton as well as sub generators that allow the developer to quickly scaffold various UI and API components. The generator supports a number of customizations through questions asked before generating the app. The ones I found most useful were:

Client Side

  • Html templating : HTML, PUG (previously Jade)
  • Angular Router : ngRouter, ui-router
  • Stylesheets : css, stylus, sass, less
  • CSS frameworks : bootstrap (with the option to include UI Bootstrap)

Server Side:

  • Scripts : javascript, Typescript
  • Databases : none, Mongodb, SQL
  • Authentication boilerplate
  • oAuth integration with Facebook, Twitter and Google Plus
  • Socket IO integration

Phew! That was a lot of options built into the generator itself, stuff that teams and products usually like to customize according to their convenience. This by itself is a strong reason to select the framework, because none of the other frameworks that we evaluated came anywhere close in terms of customizability and out of the box functionality. The generator also comes with built in hooks to deploy your application to Heroku or Openshift, although I found that part to be a little broken (more on that later)

A lot of things have changed though, since my last experience. For one, the guys over at generator-angular-fullstack added support for Typescript. Typescript in fact, is a superset of javascript, but brings a number of enhancements (including transpile time type safety) to the table. On the other hand, the generator still works with Angular 1.x, although the alpha version does support Angular 2. But then, working with the alpha version for a project needing quick turnaround times didn’t sound like an exciting thought.

Anyway, coming back to getting started with the application.

Getting Started

Installing Yeoman

 npm install -g yo

Installing the angular fullstack generator and its prerequisites

npm install -g yo gulp-cli generator-angular-fullstack

On a side note, please read node-gyp’s installation guide before going any further to get the application to run successfully. Node-gyp is required to compile native drivers for each platform and on windows, there are a couple of different ways to support the compilation process. Personally, I was able to get option 2 on the link mentioned above working (see: “Option 2: Install tools and configuration manually”)

Initializing the App

Finally! Coming down to the crux of the matter. Initializing the app

Run : yo angular-fullstack

The installer asks a number of questions about customization, including the ones mentioned above, and once the installer has completed, you have a fully functional app (with authentication if you selected it during install) ready for you to work on.

Running the app is as simple as running : gulp serve

You just need to make sure that if you selected a database, it is running on your local box so the node API can connect to it. If the DB is not found, the application will simply crash, but you already knew that would happen 🙂

Stay tuned for the next article about the getting familiar with the code generated by the Yeoman generator

Most frequently asked .NET interview questions for 5 years or less
 
  1. What is the difference between System.Array.CloneTo() and System.Array.CopyTo()?
  2. What is the difference between an interface and an abstract class? Give examples of their use in real life?
  3. Can you use “this” with the static class?
  4. What is the primary difference between “read-only” and “constants”?
  5. What is a garbage collector? Can we force the garbage collector to run? Is that guaranteed that it would run?
  6. What is public, static, void and main?
  7. Can we execute multiple catch blocks written for same try block?
  8. What is the difference between Finalize() and Dispose() method?
  9. What is a sealed class in C#? Explain with examples?
  10. What is the difference between a HashTable and a dictionary? When to use what? Give an example of each?
  11. What is “out” and “ref” parameter in C#?
  12. What is “protected internal” in C#?
  13. What is a “finally” in exception handling? How does it differ from finalize?
  14. What is generics?
  15. What is the difference between a connection pooling and an object pooling? How and where do you set the connection pooling parameter?  What is the default value?
  16. What is multiple inheritence? Is it allowed in C#? How do you achieve that?
  17. What is boxing and unboxing? Give examples of each?
  18. What is a copy constructor?
  19. What is a static constrictor?
  20. What is the difference between overriding and overloading? Give examples?
  21. What do you mean by virtual method?
  22. What types of commets are used in C#?
  23. What is abstraction, inheritence, polymorphism and encapsulation?
  24. What is the relation between data hiding and encapsulation?
  25. What all the access modifiers you have in C#?
SMART Goals – You really have to be smart in setting your goals
 

“Know what you want to do, hold the thought firmly, and do every day what should be done, and every sunset will see you that much nearer to your goal.”
Elbert Hubbard

GOAL – A goal is a description of a condition one wishes to achieve. It is the desired result or possible outcome that a person or a system envisions and commits to achieve.

If there is no goal, there is no direction. “Being happy” is not a goal because it does not describe the specific condition.  Instead, “I would travel to Europe this year” is a goal.

The GOAL should be SMART. This acronym extends to Specific, Measurable, Attainable, Realistic and Timely. This is indeed very powerful tool while hardly used.

S – Specific
If you don’t express your goal in specific terms, it is very difficult to achieve. Moreover, you will never know whether you have achieved your goal or not.

Examples
Ambiguous/Vague  – I want to lose weight.
Specific – I want to lose 5 kg in next 90 days.

M – Measurable/Meaningful
You must have concrete criteria to achieve your goals.  You should be able to measure your result or outcome to ensure you are on track. The goal will be really meaningful when you attach motivation to it.

A – Achievable/Attainable
Goals should be motivating and challenging while do ensure that it’s not virtually impossible.  The moment you define your goals and start working on them, it starts coming closer. Things get easier.  Attainable doesn’t mean choosing very simple goals.  The tough goals stimulate you to do more and expand your comfort zone.

R – Realistic/Relevant
The goals which are not realistic, you are highly unlikely to achieve them. Although nothing is impossible but the exceptions are rare.  For instance, if you decide to go for ACP certification with little agile knowledge, assuming you will read 5 books in 5 days, the chances are fat that you will have a success.

T – Timely/Timebound
It is critical to specify a timeline for achieving your goals. If the goal is for the long term, break them down into smaller multiple goals to hit your ultimate goal. This would keep you motivated throughout the journey. For instance, you want to rank number one blogging site for Agile in 24 months, you can target to get into first 1000 in 6 months, 100 in a year, 10 in 1.5 years and eventually number one in 2 years.

Guidelines

  1. Give a deep thought, identify your goals, discuss if needed.
  2. Write them down clearly.
  3. Review them regularly.
  4. Track your progress.
  5. Update your goals as required.
  6. Take the complete ownership of your goals.
  7. Short term goals need to be more realistic. The long term should be broken down into multiple short term goals.

The “Law of Attraction” principle works very well with your goals. If you constantly keep looking at your goals every day, then the chances of achieving them become very high. According to “Law of attraction”, if you can convince yourself of something, the whole world support you to achieve that.  The self-motivation/self-realization/self-acceptance of accomplishing a goal is more important than putting an effort has been proven many times.

The people will treat you the way you treat yourself.  If you think, you would get promoted and you convince yourself that it would happen, it is very likely that it will happen. In order to convince yourself, you should set SMART goals. This will be one of the inputs for “Law of Attraction” to work. You must have noticed that if you want something desperately and constantly focusing on that, you will just get it. In the process of desperation, you actually work on convincing yourself.

Getting Started with the MEAN stack (Mongodb Express Angular Node) – What is MEAN
 

I’ve been helping out some friends with setting up a new site for their endeavors. The basic requirements were

  1. The site needs to be a ‘single page application’ (SPA)
  2. Should be light weight
  3. Should be easy to deploy to one of the many available hosted environments

MEAN stands for the set of technologies used in application development, much like the LAMP (Linux, Apache, MySql and PHP) stack before it. The technologies and frameworks involved in the MEAN stack include Mongodb, Express Js, Angular Js, and Node Js. From a comparative standpoint, I believe that MEAN is popular today, for many of the same reasons that the LAMP stack gained popularity earlier.

Despite their limitations, both development stacks received a strong push from the community, have ubiquitous ‘Hello, World!’ tutorials, are supported on a number of cheap (and sometimes free!) PAAS hosting providers, and required little to no prior experience to get off the ground, giving instant results with minimal effort. They might not be the best dev stacks of their times, but the sheer inertia from their communities has also played a major role in the two being among the most popular web development platforms in the world today.

Why use the MEAN stack

One of the primary advantages of the MEAN stack that the code is written in Javascript, through all layers of the stack. This means that the programmer’s experience with one language (Javascript), is reused for everything, including persistence and server side code (in addition to the usual client side manipulation using a UI framework, which in this case, happens to be AngularJS)

The other big advantage of having javascript at all levels in your dev stack is that objects don’t need to be marshaled and unmarshaled when moving from one layer to another, usually removing the boilerplate code responsible for such conversions. This also helps developers take advantage of Javascript’s loosely typed nature to manipulate data as and when needed. Considering that Mongodb is a document database, and ‘documents’ don’t really *need* to have a fixed schema, this lines up pretty well with Javascript’s the loosely typed nature allowing us to do some really interesting things.

One of the drawbacks that I have personally experienced, however, of the MEAN stack is that developers with prior experience primarily in relational databases tend to continue to think in terms of tables. Relating collections to tables, and documents to records isn’t wrong, conceptually, but the patterns for relational patterns don’t necessarily lend themselves favourably to NoSql databases. Relational databases tend to have long, mature histories with a standardized set of interfaces and features that a developer can reasonably expect to get if he chooses any of the competing options out there.

Sadly, in my experience, NoSql is nothing like that. Different implementations (read databses) have widely differing ideologies on the ‘Right Way’™ of doing things, and they are correct! This is mostly because each implementation seems to be built for a slightly different use case, that needs different trade-offs to make the system function efficiently (for the chosen scenario). This doesn’t mean the databases can’t be used for anything outside their original intended mainline use cases, just that the default settings for the system may not be the best for you. The minor differences in behaviors also means that again, patterns identified for one NoSql database may not be the best for a different one.

While this may change in future as the stack matures and ‘enterprise patterns’ (I hate that term, but it seems apt for this situation) emerge and become ‘common knowledge’ ingrained in a majority of the developers out there, this is not the case today.

Check out the next post on how we got started.

MEAN stack Part 2 – Yeoman and generator-angular-fullstack

Top 20 leadership interview questions which you must prepare in advance
 

Have you ever noticed that the questions asked during leadership interviews are so easy and everything went so well but still you were not selected? Or probably you could have answered slightly different then what you did. The questions seem so easy but your selection would be decided not based on how many questions you answered but the quality of your responses.  The key is to prepare well and that’s something many of us don’t do it very well. Whenever you go for an interview, you must write down all the questions post that interview and think through that what you could have answered or how would you have responded. The preparation is most important. If you attend 10 interviews, you would find, a majority of the questions are keep getting repeated. I am not providing an answer to any of the questions listed below as the answer depends on your role, the company you are going for an interview, culture, future expectations etc. etc.  There is nothing wrong or right in leadership interview. It is all about how do you articulate and respond to different situations. Following are must prepare questions well in advance in order to increase your chances of not only higher success rate but getting better role and money.

1. Tell me something about yourself?

Tip: You know too much about yourself and it is quite tough to articulate the most important part upfront. Prepare well for this question. This is something you would hear almost all the times in some or other form.

2. Explain your current project/s and your role?

Follow up question – Sell your product to me.

Tip: Preparation is key here as well. What you are talking should show your knowledge and strengths. Don’t forget to get that aligned for your job you have come for an interview. If you can answer “what is there for me” from interviewer perspective, you have won half the battle.

3. What is your biggest weakness?

Follow up question – What did you do to overcome your weakness?

Tip: This is the question where interviewer expects you to open up and further wants to know what you did about it. It’s not a perfect world.  It’s highly impossible that individual doesn’t have a weakness.

4. What is your biggest strength?

Follow up question – How did you leverage it to support your organization?

Tip: How can you align that with your upcoming job needs?  You’re a great cook but does it really help?

5. How do you motivate your team?

Tip: Provide your answer with an example.

6. How do you manage conflicts between two members or among the team?

Tip: Answer the question and justify with an example. Everyone can talk bookish theories while implementation gets more priority in this case.

7. Why should we hire you? What is that you could do which others can’t?

Tip: You should know your prospective company where you are going for an interview well in advance. Moreover, you should talk about how your success and knowledge align with interview company’s expectations.

8. Did you ever fail? Did you make a blunder? A decision what you have taken and you regret it?

Follow up question – How did you later get that corrected?  What did you learn from it?

Tip: Fail faster succeed sooner. If you have never failed either you are a god which is highly unlikely or you are faking it. Talk about the situation and be ready for follow-up question as an interviewer is more interested in knowing what did you learn and how would you avoid that situation in future.

9. Where do you see yourself in next 5/10 years? How are your short terms and long term goals?

Follow up question – What are you doing to achieving them?

Tip: You must be able to justify for what you say. I have seen people saying software development or managing a larger team but unable to align that with their future goals.

10. What is your passion? How do you keep that alive?

Tip: I say, my passion is reading and when asked what the last book you read is, you don’t have a concrete answer. Weird? Off course yes.

11. What are your salary expectations?

Tip: If you don’t plan this question or prepare to answer in advance, it is highly unlikely that you will be able to convince your interviewer with real expectations.

12. What do people criticize about you?

13. Why are you looking for a change?

Tip: No company is perfect and there are always challenges. Don’t talk ill about your current organization.  

14. What is the most difficult part of being a leader?

15. Tell me a situation where you had to make a tough decision which was supporting your company’s goal while that had a short-term financial impact?

Tip: Leaders take big decisions and you are one among them. If you are instruction follower you are not a leader.

16. Would you compromise your team member pride over company’s purpose?

Tip: There is no perfect answer for this. It all depends. To you, what is right is more important. You should have an example else you are in deep trouble.

17. What are three most critical things for you as a leader?

Tip: As a leader, one of the best things which I learned are people, business alignment and building relationships.

18. Did you ever fire anybody?

Follow up question – What is the process? How did you go about it?

Tip: Be honest about whether you have done or not. In this competitive world, you have to let go non-performers. You must know the process around it. (Read about Performance Improvement Plan)

19. How do you handle stress and pressure?

Tip: It is very obvious that you will have challenges. You can’t say that everything is great and I manage them so good. If that’s the case, you may not be even looking for a change.

20. What is your biggest achievement in your career as a leader?

Tip: If you don’t prepare, you may answer right but chances are slim that you would be articulate it well.

In case if you encounter any other question/s which you found it interesting, please post it in the comment below. Thanks in advance!!

TDD (Test Driven development)
 

There are lots of practices that need to be followed while doing XP as an agile methodology. And one of them is automated testing. However, there is lots of confusion in the tech industry if you want to test the behavior of the system or the subunits/parts of the system. First, lets us understand these terminologies. In this post, we will talk about Test driven development.

TDD (Test Driven development)

TDD or Test Driven development is an approach in which unit tests drive the development of the code. That is, when there is a new feature that needs to be developed, the unit tests corresponding to the feature is developed first before the actual code need to create the feature is coded.

Let’s take an example. Let’s say at a point of sale system, we need to calculate the bill based on the list of products picked by the consumer. Let’s write unit test corresponding to this code. (I have used C# based XUnit as the unit testing framework)

        [Fact(DisplayName = "SimpleBiller Should Calculate Total bill Amount")]
        public void SimpleBillShouldCalculate()
        {
            //Given
            var ProductsList = new List();
            ProductsList.Add(new Product { Name = "test Product1", Price = 5 });
            ProductsList.Add(new Product { Name = "test Product2", Price = 5 });
            var simpleBill = new SimpleBiller();

            //When
            var bill = simpleBill.GenerateBill(ProductsList);

            //then
            Assert.Equal(10, bill.TotalCost);
        }

In the above Unit test, we have 3 parts.

  • Given
  • When
  • Then

Given

This is the known part of the problem. i.e in mathematical terms, it’s part of the problem. In the example, we have initialized the variables and known things corresponding to the products (selected by the consumer) and the Biller object.

When

This is the business action based on which we are writing the code. In this case its GenerateBill action/method.

Then

The purpose of the tests is to ensure that the code/action does it properly as per the plan. In order to do that, we are asserting the assumptions/result of the method we are testing. In our case, we are asserting the total amount that the bill will have to be generated for.

Running the test

There are three stages of running the test.

  • Red – When we run the test now, it will fail as there is no code corresponding to the calculate bill functionality.
  • Green – In order to fix the above test, let’s write the real code corresponding to the above unit test/requirement.
        public Bill GenerateBill(IEnumerable products)
        {
            var bill = new Bill { Products = products };
            foreach (var product in bill.Products)
            {
                bill.TotalCost += product.Price;
            }

            return bill;
        }

Now, when we call GenerateBill method from the test, it will return the Bill with the total amount.

  • Refactor – With the above code written corresponding to the test, we are sure the functionality is correct as per the requirement. But the code is not optimal, as the foreach loop can be reduced to a simple C# LINQ  expression.
        public Bill GenerateBill(IEnumerable products)
        {
            var bill = new Bill { Products = products };
            bill.TotalCost = bill.Products.Sum(x => x.Price);
            return bill;
        }

Conclusion

TDD is a foolproof approach to developing software as per the requirement. The test also provides confidence to the developers on the edge conditions and other possibilities in the code. However, there is an alternative thought that TDD could waste developer time. Do you think, TDD is the right approach to software development? Please provide your comments.