Wednesday, 21 April 2021

Uncle Bob - Just what I need when we have a pandemic!

https://blog.cleancoder.com/uncle-bob/2015/10/30/FutureProof.html

I can read this blog over and over again....some of it makes sense...most of the time.

https://blog.cleancoder.com/uncle-bob/2018/04/02/InTheLarge.html

Tuesday, 24 March 2020

I've been thinking - there's only two types of production issues

1). A temporary infrastructure problem pops up at all hours of the day or week and takes the entire application out. At best kicking the users to the logon screen, worse case, ugly dirty error screen with a full load of stack information. Question is what damage has been done to the data? Who knows? Who cares? What if it happens again? Can infrastructure provide a guaranteed fix?

2). More serious a defect(s) in the application which means a code fix. These are the ones that can be reproduced and they don't go away no matter how hard you try until the code has been fixed. Fixed, now it's time to jump through the loops of unit/integration testing(if your lucky), system testing, UAT testing and Preproduction smoke testing.

Do we have to do a data conversion or fix? Whats the impact? How long will it take?

Finally the out of hours deployment and smoke testing before allowing the users back on to the application.

Does Application Support have documentation to support the change(s)?

To be fair no matter how well an application has been developed, edge cases will present themselves and sometimes at the most inappropriate times. Good luck with that!

COV-ID19 and working from home, before the end of my current contract!

Well two years and the application finally went live in December 2019. I'm at home doing application support - documentation of the failed ServicePulse messages which really means why is the application falling over, plus poor performance, being just a handful of issues for a handful of users too- NO UNIT TESTS, NO AGILE, NO TEAM WORKING AS ONE = POOR APPLICATION.

IR35 has been postponed, with the contract market shrinking faster than a whore dropping her draws who knows what will come next.

What next, not sure, just blog for the next three months. Think I will never find a true agile contract, there must be some out there. Real people wanting to have a work life balance delivering a quality application.

Whatever happens next stay safe, stay well, keep doing Agile.

PS. Next time I will not hang about bashing my head against a wall.

PPS June 2020, Found the perfect contract, or I hope so. :-)

I have just spent nearly two years trying to get a project to become Agile and failed, as the Team Lead was too busy playing politics.


The bulk of the code (99% of the code ) has no unit tests and now they have been told to retro fit them. Depressed, yes, happy I'm moving on, you bet. There's only so much headbanging against the wall you can do before it hurts. Then you stop. I should have stopped a long time ago, why didn't I, cause I wanted to push this monster across the line. Shame on me. But in my heart I'd hoped that they would listen and become Agile.

1). Did the team understand the meaning of Agile?
No. They likes the word and liked using it, but at the end of the day they didn't understand despite repeated attempts to make them understand. The key values of Agile e.g. NOT, working as a team and helping others. Even the Team Lead took the words in one ear and let them fall onto the floor out the other ear.

2). Apathy, resisting change.
There maybe more than one reason why people don't want to change deep down. Loss of status with the change of the old guard going to the new stateless flat team structure. Or they just want to be seen doing Agile and shout the key words about but still sit down and do it their way. Reminds me of a song.

3).Make over, not!
So everyone still loves the old school ways and the team want to appear modern and up to date, so just used the words whilst walking around the office e.g. I'm Agile darling don't you know, it's hot right now. When really it's time for change out with the old and in with the new. Why have so many waterfall projects failed, elephant burgers. Why not try eating a quarter pound burger of cut the elephant burger up in small chunks.

4). The minute someone says it costs more!
So Agile is more expensive as you deliver quality testable code.In bite size chunks that the user can commit to and sign off on at regular intervals, sprints. They also get to make changes for the better as they may have misunderstood or missed out functionality. It also means that when you hand over to support there's less panic as the application is more stable and documented with unit tests that CI/CD run.

5). Sprints, two weeks, three weeks or four weeks,Sir!
So frequent deliveries are over kill, really! Small is beautiful, small changes are easy to test, small changes are made at a quality pace. It give the development, system test and UAT teams discipline as to the application being in manageable parts and no one has that elephant burger to test.

6). We are Agile, just to attract new people.
Really, how long do you think they will be impressed with you and the environment. Most will stay a matter of months then go. The excuse we are going agile then some month pass and still no progress has been made. the key to successful management of developers is to keep ahead of the curve or at least on it. Waterfall is dead it never worked, get over it.

7) No, don't do it - waterfall with agile.
Why, just why would do this I have no ideas. Agile allows the entire team from Application support, UAT, System testers to get involved and see the application from birth to delivery. No surprises along the way, better understanding for all, transfer of knowledge in key functionality and process. Come everyone just do it - go Agile and stick to the core values unlike the Team Lead who likes to hear the sounds of his own voice at the stand ups, or daily argument meetings as the development team called them - amongst other things too rude to mention.








Thursday, 21 December 2017

Memory Jogger for Me - Object Lifetime Management...

Lifestyle
Description
Disposal
A new instance of the component will be created each time the service is requested from the container. If multiple consumers depend on the service within the same graph, each consumer will get its own new instance of the given service.
Never
For every request within an implicitly or explicitly defined scope.
Instances will be disposed when their scope ends.
There will be at most one instance of the registered service type and the container will hold on to that instance until the container is disposed or goes out of scope. Clients will always receive that same instance from the container.
Instances will be disposed when the container is disposed.


Lifestyle
Description
Disposal
Within a certain (explicitly defined) scope, there will be only one instance of a given service type A created scope is specific to one particular thread, and can’t be moved across threads.
Instance will be disposed when their scope gets disposed.
There will be only one instance of a given service type within a certain (explicitly defined) scope. This scope will automatically flow with the logical flow of control of asynchronous methods.
Instance will be disposed when their scope gets disposed.
Only one instance will be created by the container per web request. Use this lifestyle in ASP.NET Web Forms and ASP.NET MVC applications.
Instances will be disposed when the web request ends.
Only one instance will be created by the container during the lifetime of the WCF service class.
Instances will be disposed when the WCF service class is released.


The problems with MSBuild...

So I started to use MSBuild for our current clients CI server, told them to use TeamCity, Go, ninja or Octopus but they would not listen.

So I found myself try to debug the scripts. Ops! Big mistake I had to add yet more code to understand where I was going wrong. Therein lies the problem the scripts  become over complex and hard to understand let along document for the next poor sap!

The next problem I found was that the build server and my local VS2017 had two different MSBuild versions – why am I surprised I shouldn’t be it’s the way of the world or maybe I’m an alien!

Versioning was my next stone wall – I found that generated files are almost impossible to version using MSBuild – not for the faint hearted and I could only find advance topics on the matter, as time was against me I left that for a much later date. Why, it’s should be the same as a source code file or assembly info file.

As MSBuild is now open source everyone can jump and mop up the long awaited defect fixes that Microsoft never got round to. I for one will be jumping in b with both feet first or nag my current client until they finally given in.


Why I hate TFS, most of the time actually…

So I’m not in the best frame of mind today having being hit by TFS automatic merge even when I have it turned off it still thinks it’s smarter than the average bear, not!

Yes I have used PVCS, VSS and SVN for my sins in my professional career all of which I hate with the same if not less passion as I do TFS.

I my humble opinion Microsoft promised so much more when you moved to TFS from VSS, but it evaporated along with the morning mist!

VSS every time you looked at a file it would check it out without warning you. Try looking at a resource file in TFS and bang! Config file checked out.

TFS branching is poor compared to the rich functionality of GIT. Yes, I know you can use GIT from the VS/TFS interface but the client dictates the technology stack at the end of the day.

MS Build – one again so yesterday in my opinion Go, TeamCity and many more are so much better – agreed the implementation is the key but that aside they are so much better and informative when things go awry.

At one site I worked at, they migrated from VSS to GIT the Holy Grail in my opinion. I could was on about the feature rich functions but I will not just try it for yourself and see…enjoy.


The current contract I’m working at I have been waxing lyrical about Bitbucket, JIRA and Confluence that every other comment relates back the three best products in the market place today. 

They in turn bounce at back at me whenever I mention or they mention code repositories, CI or CD or SharePoint – YUK! I can’t believe I said that word. Another pet hate.

Tuesday, 21 November 2017

NServiceBus ...


So while working for a well known Insurance company in Gloucester I was asked to build and document a service bus. After thrashing around with ReBus I convinced the client to go with NServiceBus - what a saga, turing a dramas into a saga...now!

NServiceBus is really a distributed messaging layer. It allows for all sorts of communications between processes, you can choose from:
                Peer to peer
                Pub/sub
                Send to self
                Broadcast to all

However at the end of the day what makes this all possible is the central backbone of NServiceBus.
These days NServiceBus also offers a cloud based offering. In this article I will however be focusing more on the regular NServiceBus installation, which is by using NServiceBus within an organization using MSMQ.

Transactional
This uses the standard Distributed Transaction Coordinator, to allow inter process transactions to occur. What the NServiceBus framework does is that it will only commit a Transaction when a message (or complete Saga) is completed. If an Exception is seen within a message handler, NServiceBus will possibly carry out n-many retries (you must configure this), after which it will roll back the transaction.

Durable
As NServiceBus uses MSMQ as a transport (or Azure, but as I stated we are not discussing that in this article). All messages are safe, and will be maintained even after the loss of power. The usual MSMQ benefits are available.

Reliable
This is partly achieved thanks to the use of MSMQ and also thanks to the fact that NServiceBus will persist things at various stages in its messaging pipeline. As previously stated this could use MSMQ/Raven or SQL storage. This article will talk about the use of SQL storage for persistence.

Distributed
The fact that we could distribute handlers/publishers across an entire network, allows us to completely distribute our messaging layer.

Scalable
NServiceBus provides a load balancer called "The Distributor". I will not be covering that in this article, but if you think you would like to load balance your messaging components, "The Distributor" may be for you.

Setup
As previously stated NServiceBus provides a common messaging layer interface for the demo app we will be looking at using NServiceBus to accept a Command and then use a Message.
This diagram may help to illustrate this further.

It can be seen that NServiceBus provides the common messaging layer backbone (for want of a better word) and that each of the processes that deals with the messages (known as an endpoint in NSB speak) has a MSMQ. It is important to note that this is only one possible configuration of how to use NServiceBus. You really can configure it to suit your needs. The above diagram is just how I chose to do it for the demo app.

Messages
It is fair to say that NServiceBus is all about the messages. If you want to send a command or an event to a NServiceBus endpoint, it will take the form of a message. So what exactly is a message? Put simply it is a shared contract that all parties know how to deal with. The messages are serialized by NServiceBus into the serialization format you choose (There are many choices here Xml, Json, Bson, Binary etc, etc), and deserialized by the endpoint(s) that deal with the messages (via the use of configuration and the expected handlers). If you come from a WCF world, you can think of messages as the objects that are shared between client and server.

[DataContract]

There is a distinction between "Command" messages and "Message" messages, but we will discuss this later. For now let's just see an example of the code for both.

Command
namespace Messages.Commands
{  
   public class CreatePurchaseOrderCommand
   {
        public int PurchaseOrderId { get; set; }
        public string Description { get; set; }
    }
}

Message
namespace Messages.Message
{
    public class CheckPurchaseOrderStatusMessage
    {
        public int PurchaseOrderId { get; set; }
        public string ConfirmationDescription { get; set; }
    }
}
As you can see the Command and Message classes are just standard .NET classes, nothing special about them at all. We will get to the bit where we discuss the importance between Commands and Message, but for now just note that these messages are just regular .NET classes that allow you to add whatever data you want to them. You can be reassured that NServiceBus will make sure that the values for these messages will be stored when needed.

Commands Vs Messages
Ok so what exactly is the difference between a command and a message. Well to understand that a bit further, let's consider the following scenario.
We wish to design an ordering system something like Amazon, where we allow the user to place an order. When an order is placed by the customer it should be dispatched and email is sent to the client notifying them of the purchase.

OR
Command => DoSomething (multiple senders, single receiver)
Event => SomethingHasBeenDone (single sender, multiple receivers)
Message => request/response (base class of other 2)


Now that is a pretty simple workflow, but how do "Commands" and "Messages" fit into that?
Well if we break it down we can imagine something like the following:
Action                                                    Command Or Message?
Place order                                           Command to start the work flow
Dispatch order                                     Message that could advance the workflow
Email client order confirmation        Message that could advance the workflow

Still not clear?

Ok so let's try some words. I find it helps to think of things as follows:
Command : Is something that is about to happen. Typically this would be a 1..1 type of message.
Message : Something that may continue the current long running process. This would typically be sent the current endpoint, and would more than likely be a 1..1 type of message.

NOTE : The more eagle eyed amongst you may think that rather than having one big workflow we could possibly have multiple endpoints, one for DispatchOrder, and another for EmailConfirmationToClient. The difference being is that if you chose to go down this route, you would need to send a message to a new endpoint rather than locally
NServiceBus also supports the idea of publishing events, this would typically be used when you want more than one endpoint to act on some event. In fact it should come as no surprise that NServiceBus distinguishes this type of message as an "Event" that is broadcast (via Bus.Publish(...)) to all interested endpoints. This is not done in the demo app, but rest assured it is completely possible, and is easily achieved by using

NServiceBus. Thing is at the end of the day this is an architectural decision that only you can make.
More information of messaging type distinctions can be found at NServiceBus web site.
These web sites will give the types of message patterns used as a defacto.
http://www.enterpriseintegrationpatterns.com/patterns/messaging/EventMessage.html
http://www.enterpriseintegrationpatterns.com/patterns/messaging/CommandMessage.html

Hosting The Bus
NServiceBus offers a few hosting solutions, you may choose from:
1). Running the standalone NServiceBus.Host.exe executable.
2). Hosting NServiceBus inside a windows service, which just runs the standalone NServiceBus.Host.exe executable.
3).Completely self hosted.

Sagas
Long-running business processes exist in many systems. Whether the steps are automated, manual, or a combination, effective handling of these processes is critical. NServiceBus employs event-driven architectural principles to bake fault-tolerance and scalability into these processes. The saga is a pattern that addresses the challenges uncovered by the relational database community years ago, packaged in NServiceBus for ease of use. One of the common mistakes developers make when designing distributed systems is based on the assumptions that time is constant. If something runs quickly on their machine, they're liable to assume it will run with a similar performance characteristic when in production. Network invocations (like web service calls) are misleading this way. When invoked on the developer's local machine, they perform well. In production, across firewalls and data centres, they don't perform nearly as well. While a single web service invocation need not be considered "long-running", once there are two or more calls within a given use case, take issues of consistency into account. The first call may be successful but the second call can time out. Sagas allow coding for these cases in a simple and robust fashion. Design processes with more than one remote call to use sagas. While it may seem excessive at first, the business implications of the system getting out of sync with the other systems it interacts with can be substantial. It's not just about exceptions that end up in the logs.

My Implementation:
We have a simple console app with a service base inherited into the program class to all us to perform the start-up of the process.  As per the following code sample:
(Full project resides in Presto.ESB.SagaTemplate)
using NServiceBus;
using NServiceBus.Logging;
using NServiceBus.Serilog;
using Serilog;
using SimpleInjector;
using SimpleInjector.Lifestyles;
using System;
using System.ComponentModel;
using System.ServiceProcess;
using System.Threading.Tasks;
using Container = SimpleInjector.Container;

namespace Mikeys.ESB.SagaTemplate
{
    /// <br />
<summary>
    /// Used by NServiceBus DO NOT REMOVE
    /// </summary>
    /// <seealso cref="System.ServiceProcess.ServiceBase">
    [DesignerCategory("Code")]
    public class ProgramService : ServiceBase
    {
        /// <summary>
        /// The endpoint instance for the current Saga Service
        /// </summary>
        private static IEndpointInstance _endpointInstance;
        /// <summary>
        /// The logger writes to log file, all information and errors
        /// </summary>
        private static readonly ILog Logger;

        /// <summary>
        /// Initializes the <see cref="ProgramService"> class.
        /// </see></summary>
        static ProgramService()
        {
            // Configure container.
            var containerForIoc = new Container();
            containerForIoc.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();
            containerForIoc.Register<inservicemessagehub nservicemessagehub="">(Lifestyle.Singleton);
            containerForIoc.Register<sharedjobservice sharedjobservice="">(Lifestyle.Singleton);
            containerForIoc.Verify();

            // Configure logging.
            Log.Logger = new LoggerConfiguration().WriteTo.ColoredConsole().WriteTo.RollingFile(@"c:\\Presto\\logs\\Log -{Date}.log").CreateLogger();
            LogManager.Use<serilogfactory>();
            Logger = LogManager.GetLogger<serilogfactory>();
        }

        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        public static void Main()
        {
            using (var service = new ProgramService())
            {
                Logger.Info("Configuring service.");

                Console.Title = "SagaTemplate Console Application";
                // To run interactive from a console or as a windows service
                if (Environment.UserInteractive)
                {
                    Console.CancelKeyPress += (sender, e) =&gt;
                    {
                        service.OnStop();
                    };
                    service.OnStart(null);
                    Console.WriteLine("\r\nPress enter key to stop program\r\n");
                    Console.Read();
                    service.OnStop();
                    return;
                }
                Run(service);
            }
        }

        /// <summary>
        /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM)
        /// or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args" />Data passed by the start command.
        protected override void OnStart(string[] args) =&gt; AsyncOnStart().GetAwaiter().GetResult();

        /// <summary>
        /// Asynchronous the on start.
        /// </summary>
        /// <returns></returns>
        private static async Task AsyncOnStart()
        {
            try
            {
                var endpointConfiguration = new EndpointConfiguration("SagaTemplate");
                NServiceMessageHub.EndPointConfiguration(endpointConfiguration);
                _endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.Fatal("Failed to start", exception);
                Environment.FailFast("Failed to start", exception);
            }
        }

        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM).
        /// Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop() =&gt; _endpointInstance?.Stop().GetAwaiter().GetResult();
    }
}

The Saga processing for this is processed by the ProcessOrderSaga class (plus same named interface) with its own model ProcessOrderSagaData both these classes are for education and can be cloned and used by the developer. The bulk of the models will live in the Presto.ESB.Messages. These will define commands, events and messages and all such models. Being suffixed in the name for the appropriate type.

public class DispatchOrderCommand : ICommand
public interface IOrderActivityEvent : IEvent
public interface IOrderDispatchedMessage : IMessage

</serilogfactory></serilogfactory></sharedjobservice></inservicemessagehub></seealso>

Friday, 31 July 2015

BDD vs. TDD - No contest!

BDD (behavior driven development) is the practice of writing an executable testable specification that describes the application’s behavior. This specification is often written in a fluent interface, or in plain English
Testing features of the application and verifying the user requirements have been met.

While in TDD (Test Driven Development) the focus is on writing tests that single out units of the application. Using mocking or not there are basically three kinds of unit tests, happy, unhappy and edge case tests.

Integration tests are also of good,  making sure that the application runs end to end. e.g. the C# DAL(Data Access Layer) accessing the database and returning expected and unexpected results with the code dealing with both scenarios.


Red,Green, Re-factor, here you write the unit test prior to writing the code, it fails. Then you write the code to pass the test, the test passes. Does it need re-factoring? Now's the time  to do it. Does it meet the requirements? If not start over again and this time think more about what is required. It takes time, 6 months on average, to become a good TDD developer no matter what language you use.

Top 5 TDD Mistakes

1. Not using a Mocking Framework
2. Too Much Test Setup
3. Asserting Too Many Elements
4. Writing Tests Retrospectively
5. Testing Too Much Code

My pet hate is when someone says we are doing Agile and not doing TDD, then your not doing Agile!

For years now I have struggled to make people see the benefit of TDD, even when I interview people who say they have TDD, they don't. What they confess to is number 4 writing tests retrospectively. I must be from another planet!

Thursday, 30 July 2015

I hate SourceTree

One more point: can't say I like SourceTree. Still looking for a Mercurial GUI worth using. My biggest issue is that I'm a big user of annotate/blame (I have a very bad memory so finding out where/how/why a given piece of code was created or evolved is something I do at least weekly if not daily) and all the hg guis have absolute shit annotate. They also tend to look rather bad.
GitX is pretty good (I think I still prefer the original one over the Laullon gitx, but the Laullon gitx has an acceptable annotate view and look nice), and surprisingly the best annotate view I've seen so far is in bazaar's qt-based UI. The tools are not necessarily great overall (and the OSX interactions are downright weird), but the annotate is excellent.

Wednesday, 29 July 2015

Project Description



The LOOM.NET project aims to investigate and promote the usage of AOP in the context of the Microsoft .NET framework.


The concept of aspect-oriented programming (AOP) offers an interesting alternative for the specification of non-functional component properties (such as fault-tolerance properties or timing behaviour), as well as other crosscutting concerns. These are implemented as so-called aspects and at some point "weaved" to the other functional parts of the software.


The LOOM.NET approach is an approach that offers both: a static and a dynamic aspect weaver. The project was started in 2001 with the advent of Microsoft.Net and subsequently we released the first available aspect weaver for .NET. Like no other AOP-frameworks LOOM.NET significantly influences the Microsoft.NET AOP community.

How it works

Realized as a class library, LOOM.NET allows the language-independend definition of aspect code in the form of standard .NET classes. Both aspect weavers are fully binary compatible. Aspects written for Rapier-LOOM.NET would work with Gripper-LOOM.NET and vice versa.
weaving.gif



An aspect class is a special .NET class with methods constructors and fields as well. At defined join points an aspect class becomes interwoven with a target class. Interweaving, strictly speaking, means that an aspect method will be interwoven with a target class method. The aspect method itself contains the aspect code and is defined within the aspect class. It has a special aspect method attribute applied. This aspect method attribute declares a method in the aspect class as an aspect method. Not necessarily every method in an aspect class is an aspect method and has this attribute applied. Methods without this attribute will not be considered for the weaving process.


A target class is a regular .NET class. The one and only restriction is that target class methods (which should become interwoven) either have to be virtual or to be defined via an interface. The weaving process will be initiated during runtime with a factory. Instead of using the new operator one uses the weavers factory method to produce interwoven objects.

Wednesday, 30 July 2014

Common code smells!



· Duplicated code: identical or very similar code exists in more than one location.
· Long method: a method, function, or procedure that has grown too large.
· Large class: a class that has grown too large. See God object.
· Too many parameters: a long list of parameters in a procedure or function make readability and code quality worse.
· Feature envy: a class that uses methods of another class excessively.
· Inappropriate intimacy: a class that has dependencies on implementation details of another class.
· Refused bequest: a class that overrides a method of a base class in such a way that the contract of the base class is not honored by the derived class. See Liskov substitution principle.
· Lazy class / Freeloader: a class that does too little.
· Contrived complexity: forced usage of overly complicated design patterns where simpler design would suffice.
· Excessively long identifiers: in particular, the use of naming conventions to provide disambiguation that should be implicit in the software architecture.
· Excessively short identifiers: the name of a variable should reflect its function unless the function is obvious.
· Excessive use of literals: these should be coded as named constants, to improve readability and to avoid programming errors. Additionally, literals can and should be externalized into resource files/scripts where possible, to facilitate localization of software if it is intended to be deployed in different regions.
· Ubercallback: a callback that is trying to do everything
· Complex conditionals: branches that check lots of unrelated conditions and edge cases that don't seem to capture the meaning of a block of code.

Tuesday, 29 July 2014

How is Kanban different from Scrum?

Both Kanban and Scrum focus on releasing software early and often. Both require highly-collaborative and self-managed teams. There are, however, differences between the approaches:
Kanban
Scrum
No prescribed roles
Pre-defined roles of Scrum master, Product owner and team member
Continuous Delivery
Timeboxed sprints
Work is ‘pulled’ through the system (single piece flow)
Work is ‘pulled’ through the system in batches (the sprint backlog)
Changes can be made at any time
No changes allowed mid-sprint
Cycle time
Velocity
More appropriate in operational environments with a high degree of variability in priority
More appropriate in situations where work can be prioritized in batches that can be left alone
Organization, culture and team dynamics often determine which method is the best fit.